[英]Await question in Javascript async functions
async abc(){
await some().then(() => {
//do inside then
});
//other code
}
"await" 是只等待 some() 還是等待 some() 及其 then(),然后再轉到 //other 代碼? 基本上問題是,在轉到下一個語句之前,等待是否也在 then 部分完成。
some().then()
返回一個新的 promise 並且await
等待這個新的 promise,所以它會等待.then()
處理程序和它可能在經過await
之前返回的任何 promise。 換句話說,它等待整個承諾鏈。
通常,在同一語句中混合await
和.then()
並不是很好的風格,因為您通常希望堅持使用await
而不是.then()
如下所示:
async abc(){
let result = await some();
// do something with result
//other code
}
這為您提供了await
啟用的更簡單的外觀和更有序的代碼設計。
您也可以使用箭頭函數來實現這一點。
const some = () => 'something';
const abs = async () => {
const result_from_some = await some();
// do something with result_from_some
}
但是請,如果' result_from_some '中的值可能會改變,那么最好使用let而不是const
希望這可以幫助某人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.