猿问

在 Catch 块中中断异步函数

我有以下功能:


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');

      });

}

我希望这样当在承诺返回处理程序中捕获错误时,它会结束异步函数,因为我不希望它在这种情况下继续。


慕虎7371278
浏览 137回答 1
1回答

长风秋雁

取而代之的混合await使用.then(),只是await每个异步函数调用直接在try块和处理相应的错误。如果异步函数返回一个被拒绝的 promise,await将导致拒绝从try块中抛出并被捕获,跳过try.const asyncFactory = label => async () => {&nbsp; await new Promise(resolve => { setTimeout(resolve, 1000); });&nbsp; if (Math.random() < 0.25) {&nbsp; &nbsp; throw new Error(`${label} Error`);&nbsp; }&nbsp; console.log(`${label} Complete!`);};const somePromiseFunction = asyncFactory('somePromiseFunction');const anotherPromiseFunction = asyncFactory('anotherPromiseFunction');async function myFunction() {&nbsp; try {&nbsp; &nbsp; console.log('Start myFunction here');&nbsp; &nbsp; await somePromiseFunction();&nbsp; &nbsp; await anotherPromiseFunction();&nbsp; } catch (error) {&nbsp; &nbsp; console.log('Error caught:', error.message);&nbsp; } finally {&nbsp; &nbsp; console.log('End myFunction here');&nbsp; }}myFunction();您实际上可以在不使用asyncand 的情况下实现等价await,并且您不需要嵌套您的承诺来这样做:const asyncFactory = label => () => {&nbsp; return new Promise(resolve => {&nbsp; &nbsp; setTimeout(resolve, 1000);&nbsp; }).then(() => {&nbsp; &nbsp; if (Math.random() < 0.25) {&nbsp; &nbsp; &nbsp; throw new Error(`${label} Error`);&nbsp; &nbsp; }&nbsp; &nbsp; console.log(`${label} Complete!`);&nbsp; });};const somePromiseFunction = asyncFactory('somePromiseFunction');const anotherPromiseFunction = asyncFactory('anotherPromiseFunction');const oneMorePromiseFunction = asyncFactory('oneMorePromiseFunction');function myFunction() {&nbsp; console.log('Start myFunction here');&nbsp; return somePromiseFunction().then(() => {&nbsp; &nbsp; return anotherPromiseFunction();&nbsp; }).then(() => {&nbsp; &nbsp; return oneMorePromiseFunction();&nbsp; }).catch(error => {&nbsp; &nbsp; console.log('Error caught:', error.message);&nbsp; }).finally(() => {&nbsp; &nbsp; console.log('End myFunction here');&nbsp; });}myFunction();请注意,这Promise.prototype.finally()实际上是ECMAScript 2018 的一部分,因此如果浏览器本身支持它,它也将已经支持async和await. 然而,可以polyfilled而async与await不能。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答