Search code examples
javascriptasync-awaites6-promiseecmascript-2017

handle promise error first level inside try catch


function testPromise(id) {
    return new Promise(function(resolve, reject) {
        setTimeout(function() {
            if (typeof id === 'number') {
                resolve(id);
            } else {
                reject('error');
            }
        }, 500);
    }
    );
}
async function test(){
  try{
    testPromise(10)
    for(let i=0 ; i<10000; i++){
      ....
    }
    .
    .
  }catch(err){
    console.log(err)
  }
}
test();

ok consider above code I want to run testPromise function asynchronously so if I use await syntax testPromise(10) run first then for loop code run if, I don't use await, testPromise(10) run asynchronously and everything is good up to now, however, if testPromise encounter an error how should I handle it? is there any way to use async-await structure and handle this error inside a try-catch structure?
I know I can use catch function testPromise(10).catch(err =>{}); to handle error but I want to know is there any way to handle it inside my first level try-catch


Solution

  • If you want to run it concurrently with your loop and properly handle errors from both (which necessarily includes waiting for both), then Promise.all is your only choice:

    async function test() {
      try {
        await Promise.all([
          testPromise(10),
          (async function() {
            for (let i=0; i<10000; i++) {
              …
            }
            …
          }())
        ]);
      } catch(err) {
        console.log(err);
      }
    }