try/catch block not catching async/await error

折月煮酒 提交于 2019-12-06 19:36:46

A thrown error will only be caught if its directly enclosing function has some sort of error handling. Your anonymous function passed to setTimeout is not the async function itself, so the async function won't stop executing if the separate timeout throws after some time:

const makeProm = () => new Promise(res => setTimeout(res, 200));
(async () => {
  setTimeout(() => {
    throw new Error();
  }, 200);
  await makeProm();
  console.log('done');
})()
  .catch((e) => {
    console.log('caught');
  });

This looks like a good time to use Promise.race: pass it the fetch Promise, and also pass it a Promise that rejects after the passed ms parameter:

async function timeout(prom, ms) {
  return Promise.race([
    prom,
    new Promise((res, rej) => setTimeout(() => rej('timeout!'), ms))
  ])
}

(async () => {
  try {
    await timeout(
      new Promise(res => setTimeout(res, 2000)),
      500
    )
   } catch(e) {
      console.log('err ' + e);
   }
})();

This error is happening in a separate call stack, because it's thrown from within a callback. It's totally separate from the synchronous execution flow inside the try / catch block.

You want to manipulate the same promise object from within the timeout or the success callback. Something like this should work better:

return new Promise( ( resolve, reject ) => {
    let rejected = false;
    const timer = setTimeout( () => {
        rejected = true;
        reject( new Error( 'Timed out' ) );
    }, ms ).unref();
    fn.then( result => {
        clearTimeout( timer );
        if ( ! rejected ) {
            resolve( result ) );
        }
    } );
} );

It would probably work just fine without the rejected and clearTimeout too, but this way you ensure that either resolve or reject is called, not both.

You'll notice that I didn't use await or throw anywhere here! If you are having trouble with asynchronous code, it is better to write it using a single style first (all callbacks, or all promises, or all "synchronous" style using await).

This example in particular cannot be written using only await, because you need to have two tasks running at the same time (the timeout and the request). You could probably use Promise.race(), but you still need a Promise to work with.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!