亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 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 關注
  • 151 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號