为了账号安全,请及时绑定邮箱和手机立即绑定

在 Catch 块中中断异步函数

在 Catch 块中中断异步函数

慕虎7371278 2022-01-07 14:22:51
我有以下功能:async myFunction() {    await this.somePromiseFunction().then(      () => alert('Promise Complete!'),      () => {        throw new Error('Error');      }    ).catch(() => {      alert('End the Function Here');      });    alert('Do not get called if error caught above.');    await this.anotherPromiseFunction().then(      () => alert('Promise Complete!'),      () => {        throw new Error('Error');      }    ).catch(() => {      alert('End the Function Here');      });}我希望这样当在承诺返回处理程序中捕获错误时,它会结束异步函数,因为我不希望它在这种情况下继续。
查看完整描述

1 回答

?
长风秋雁

TA贡献1757条经验 获得超7个赞

取而代之的混合await使用.then(),只是await每个异步函数调用直接在try块和处理相应的错误。


如果异步函数返回一个被拒绝的 promise,await将导致拒绝从try块中抛出并被捕获,跳过try.


const asyncFactory = label => async () => {

  await new Promise(resolve => { setTimeout(resolve, 1000); });


  if (Math.random() < 0.25) {

    throw new Error(`${label} Error`);

  }


  console.log(`${label} Complete!`);

};


const somePromiseFunction = asyncFactory('somePromiseFunction');

const anotherPromiseFunction = asyncFactory('anotherPromiseFunction');


async function myFunction() {

  try {

    console.log('Start myFunction here');

    await somePromiseFunction();

    await anotherPromiseFunction();

  } catch (error) {

    console.log('Error caught:', error.message);

  } finally {

    console.log('End myFunction here');

  }

}


myFunction();


您实际上可以在不使用asyncand 的情况下实现等价await,并且您不需要嵌套您的承诺来这样做:


const asyncFactory = label => () => {

  return new Promise(resolve => {

    setTimeout(resolve, 1000);

  }).then(() => {

    if (Math.random() < 0.25) {

      throw new Error(`${label} Error`);

    }


    console.log(`${label} Complete!`);

  });

};


const somePromiseFunction = asyncFactory('somePromiseFunction');

const anotherPromiseFunction = asyncFactory('anotherPromiseFunction');

const oneMorePromiseFunction = asyncFactory('oneMorePromiseFunction');


function myFunction() {

  console.log('Start myFunction here');


  return somePromiseFunction().then(() => {

    return anotherPromiseFunction();

  }).then(() => {

    return oneMorePromiseFunction();

  }).catch(error => {

    console.log('Error caught:', error.message);

  }).finally(() => {

    console.log('End myFunction here');

  });

}


myFunction();


请注意,这Promise.prototype.finally()实际上是ECMAScript 2018 的一部分,因此如果浏览器本身支持它,它也将已经支持async和await. 然而,可以polyfilled而async与await不能。


查看完整回答
反对 回复 2022-01-07
  • 1 回答
  • 0 关注
  • 136 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号