[英]I need to run an async function from a non-async function in order (sync) - is it possible?
是的,這是一個壞主意,一個糟糕的主意。
我正在努力做到這一點:
async function delay(ms: number): Promise<void> {
await new Promise(r => setTimeout(r, ms));
console.log('called 3');
}
console.log('called 1');
(async () => {
console.log('called 2');
await delay(5000);
console.log('called 4');
})();
console.log('called 5');
輸出這個:
called 1
called 2
called 3
called 4
called 5
取而代之的是:
called 1
called 2
called 5
called 3
called 4
這可能嗎?
我取出打字稿標簽並直接在瀏覽器中運行,更改以下幾行
async function delay(ms: number): Promise<void> {
直接JS
async function delay(ms) {
它通過按順序等待而按您的預期工作......
async function delay(ms) { await new Promise(r => setTimeout(r, ms)); console.log('called 3'); } console.log('called 1'); (async () => { console.log('called 2'); await delay(5000); await console.log('called 4'); console.log('called 5'); })();
重要的是要記住 async 函數是異步的,因此沒有其他方法可以調用console.log('called 5');
call console.log('called 5');
為了不將它放在異步函數中或使用then語句......我更喜歡將調用放在異步函數中的更簡單的方法..
這並不是一個“壞主意”,而是你不能使用你想要的語法。 但是你絕對可以在async
函數之后執行console.log('called 5')
; 只是您不能使用await
(因為您不在async
函數中):
async function delay(ms) {
await new Promise(r => setTimeout(r, ms));
console.log('called 3');
}
console.log('called 1');
(async () => {
console.log('called 2');
await delay(2000);
console.log('called 4');
})().then(
()=> console.log('called 5')
);
不要忘記異步函數返回一個隱式 Promise 作為結果; 所以你可以使用then
來獲得你想要的結果。
這個,或者你把所有東西都包裝在一個async function
這樣你就可以使用await
; 但我從你的問題中了解到這在某種程度上不是一種選擇。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.