[英]Async function with for of loop and await inside, will it wait?
我對 javascript 中的循環異步等待有點困惑。 我創建了以下代碼,其中包含三個數據庫查詢。 但我不確定第三個查詢(“deleteData”)是否總是等待 for of 循環在步驟 2 中完成? 換句話說,第 2 步中的 for of 循環總是會在異步函數中的下一行執行之前完成嗎? 如果不是,我應該如何編寫循環?
async function run() {
//1. Select Data from table "userData"
const selectData = await promisePool.execute(
"SELECT user_id, firstname, lastname FROM userData WHERE user_id = (?)",
[1]
)
const parseData = JSON.parse(JSON.stringify(selectData))
const selectedData = parseData[0]
// 2. Insert each of the selected data with a loop to another table ("backupTable")
for (const el of selectedData) {
const backup = await promisePool.execute(
"INSERT INTO backupTable (user_id, firstname, lastname) VALUES (?,?,?) ON DUPLICATE KEY UPDATE firstname=(?)",
[el.user_id, el.firstname, el.lastname, el.firstname]
)
}
// 3. Delete the data from table "userData"
const deleteData = await promisePool.execute(
"DELETE FROM userData WHERE users_companyID = (?)",
[1]
)
}
run();
是的。 它會等待。 看看下面的例子。
// START OF DELAYED RESPONSE SIMULATION BLOCK function calSqr(val) { console.log(`@calSqr val=${val}`); // 2 seconds delay return new Promise((resolve, reject) => { setTimeout(() => { resolve(val*val) }, 2000) }); } // END OF DELAYED RESPONSE SIMULATION BLOCK async function printNumbers() { for(const val of [1, 2, 3, 4, 5]) { console.log(`@printNumbers calling getNum(${val})`); let res = await calSqr(val); console.log(`@printNumbers res=${res}`); console.log('----------'); } } printNumbers();
注意:使用 forEach 的 async/await 不會等待( 閱讀更多)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.