簡體   English   中英

Javascript - 異步等待不等到 function 完成?

[英]Javascript - async await not wait until function is done?

I was learning javascript with async and await and tried some example on my own, but it seems when calling the async function (func1) from another function (func2), func2 does not wait for func1 to complete its process and it jumps over and continue執行...我的代碼有問題還是應該將 func2 轉換為異步並使用 await 調用 func1? 如果是這樣,這是否意味着所有涉及 async-await 方法的函數也需要變為 async ? 這是我的原始代碼

// func1
const func1 = async() => {
   try {
     await putCallToServer(...);
     return 1;     // it returns as a promise
   } catch(ex) {
     return 2;
   }
}

// func2
const func2 = () => {
   let result = 0;
   result = func1(); // should I turn it into await func1()??
   console.log(result);  // log contains '0' instead of '1' or '2'
   return result;    // return as Promise but value inside is 0
}

如果我有一個調用 func2 的 func3,我應該把 func3 也變成 async-await 嗎?

正如評論中所述,兩個函數必須是異步的才能使用等待。 這可以在下面的代碼片段中看到。 (因為我不想在示例中調用實際的服務器,所以我在 putCallToServer() 中拋出。這是返回 2 的結果。

我還將 result 更改為 let 變量,因為您試圖 mut 一個不允許的 const。

 async function putCallToServer() { throw "too lazy to make a real error" } // func1 const func1 = async() => { try { await putCallToServer(); return 1; // it returns as a promise } catch(ex) { return 2; } } // func2 const func2 = async() => { let result = 0; result = await func1(); // should I turn it into await func1()?? console.log(result); // log contains '0' instead of '1' or '2' return result; // return as Promise but value inside is 0 } func2()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM