Hejhejhej123
Hejhejhej123

Reputation: 1195

Async function with for of loop and await inside, will it wait?

I am a bit confused about async await with loops in javascript. I have created the below code which contains three database queries. But I am not really sure if the third query ("deleteData") will always await the for of loop to finish in step 2? In other words will the for of loop in step 2 always finish before next rows in the async funciton are executed? If not, how should I write the loop instead?

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();

Upvotes: 3

Views: 964

Answers (1)

hbamithkumara
hbamithkumara

Reputation: 2544

Yes. It will wait. Take a look into the following example.

// 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();

Note: async/await With forEach won't wait (Read More)

Upvotes: 3

Related Questions