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不能。
添加回答
举报