首页 > 解决方案 > 在 catch 块中返回后继续执行函数

问题描述

使用 async / await,我尝试了两种不同的语法:

async function asyncFunc() {
    return new Promise((resolve, reject) => {
  	setTimeout(() => {
    	    reject('promise rejected')
        }, 500);
    });
}

async function asyncCallWithoutTryCatchBlock() {
    await asyncFunc().catch((err) => {
  	console.log('Catching error');
        return;
    });
    console.log('Outside, after catch is called');
}

async function asyncCallWithTryCatchBlock() {
  try {
  	await asyncFunc();
  } catch(err) {
  	console.log('Catching error');
  	return;
  }
  console.log('Outside, after catch is called');
}

asyncCallWithoutTryCatchBlock();
asyncCallWithTryCatchBlock();

我期待这个输出:

Catching error
Catching error

我明白了:

Catching error
Outside, after catch is called
Catching error

我想知道为什么在我在块中进行显式返回时console.log调用外部?asyncCallWithoutTryCatchBlockcatch

标签: javascriptasync-await

解决方案


返回值在您传递给 catch 方法的匿名函数内。因此,它仅从该匿名函数返回。作为函数中的最后一条语句,它实际上毫无用处。

两个代码片段之间的最大区别在于,一个使用语言结构 try catch,另一个使用称为 catch 的方法,该方法需要一个匿名函数。


推荐阅读