[英]Is async/await not intended for global synchronous use?
我希望這段代碼:
function resolveAfter2Seconds() {
return new Promise(resolve =>
setTimeout(() => { resolve('resolved'); }, 2000) );
}
async function asyncCall() {
console.log('calling');
var result = await resolveAfter2Seconds();
console.log(result);
}
asyncCall();
asyncCall();
要產生此輸出:
"calling"
"resolved"
"calling"
"resolved"
但是我得到了這個:
"calling"
"calling"
"resolved"
"resolved"
我必須這樣做以使我的代碼同步:
function resolveAfter2Seconds() {
return new Promise(resolve =>
setTimeout(() => { resolve('resolved'); }, 2000) );
}
async function asyncCall() {
console.log('calling');
var result = await resolveAfter2Seconds();
console.log(result);
}
const main = async () => {
await asyncCall();
await asyncCall();
};
main();
這意味着如果我在函數調用樹的內部深處有一個await調用,則必須在功能鏈中一直進行async / await才能獲得整個應用程序的同步行為? 這對我來說似乎很繁重。 請告訴我我錯了。 這絕對消除了我大部分關於異步/等待的好感:(
您的前兩個asyncCalls
重疊的原因是您不await
它們。 因此,第一個啟動超時,返回,然后調用第二個,第二個啟動超時,然后返回。
async / await是否不打算用於全局同步?
是的,沒有。 您只能在async
函數中使用await
(盡管有第2階段建議添加頂級await
),所以(無論如何,到目前為止)您不能在全局范圍內使用await
。 但是沒有理由您不能立即切換到async
功能,例如您的main
甚至只是內聯:
(async () => {
// Use await here...
})().catch(err => {
// Last-ditch error handling here
});
要么
(async () => {
try {
// Use await here...
} catch (err) {
// Last-ditch error handling here
}
})();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.