當我運行此腳本時,輸出與我預期的不同:1 到 4。這是為什么?
const delay2 = async ( ms: number) => setTimeout( () => {
console.log( '2 - timeout')
}, ms);
const mainAsync2 = async () => {
console.log( '1 - before');
await delay2( 2000);
console.log( '3 - after');
}
mainAsync2()
.then( res => console.log( '4 - done'));
輸出是:
1 - before 3 - after 4 - done 2 - timeout
uj5u.com熱心網友回復:
setTimeout本身不回傳承諾,所以awaiting 它什么都不做。它只是將超時設定為ms毫秒。相反,您應該讓您的delay2return 成為在ms幾毫秒后解決的承諾,例如:
const delay2 = async (ms: number) =>
new Promise(res => setTimeout(() => {
console.log('2 - timeout');
res();
}, ms));
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/330846.html
下一篇:如何將所有例外配置為“任何”型別
