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不能。
添加回答
舉報