iam*_*ynq 5 javascript node.js typescript
console.log('1');
await get()
.then()
.catch(() => {
console.log('2');
return;
});
console.log('3');
Run Code Online (Sandbox Code Playgroud)
为什么控制台记录 1 2 3?我想在return语句之后,代码不会被执行?
return
只会终止当前函数。在这里,被 终止的函数return
是.catch
回调。
由于.catch
返回已解决的 Promise,因此await
ed Promise 链将在解析时解析catch
。
如果您想在运行时停止外部catch
函数,请catch
返回您在外部检查的内容,例如:
(async() => {
console.log('1');
const result = await Promise.reject()
.catch(() => {
console.log('2');
return 2;
});
if (result === 2) {
return;
}
console.log('3');
})();
Run Code Online (Sandbox Code Playgroud)
或者抛出.catch
一个错误,以便外部 Promise 链拒绝。由于正在await
编辑,整个外部 Promise 将被拒绝:
const fn = async () => {
console.log('1');
const result = await Promise.reject()
.catch(() => {
console.log('2');
throw new Error();
});
console.log('3');
};
fn()
.then(() => console.log('resolved'))
.catch(() => console.log('rejected'))
Run Code Online (Sandbox Code Playgroud)
如果您.catch
没有做任何实质性的事情,但您想要这种行为,那么完全忽略它通常是一个好主意。这样,当出现错误时,await
ed Promise 将拒绝,函数将终止,并且错误可以由适当的使用者捕获。
const fn = async () => {
console.log('1');
const result = await Promise.reject();
console.log('3');
};
fn()
.then(() => console.log('resolved'))
.catch(() => console.log('rejected'))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1055 次 |
最近记录: |