-2

I am new in node js and having the problem using await function. For each should wait for the next iteration until await executes in the node. In the below code, I always get the consumptionSummaryID as 0 but I want the database insert id for next iteration for case REF.

var consumptionSummaryID=0; 
transaction.otherSegments.forEach(async function(segment){
    switch (segment.segment) {
        case 'PTD': let ptdInsertRaw= await con.query('INSERT INTO `consumption-summary` SET ?', ptdInsert);
                    consumptionSummaryID= ptdInsertRaw.insertId;  

        case 'REF':
                    if(consumptionSummaryID!=0){
                      // having code related to consumptionSummaryID;
                    }
    }
});

Please help.

Thanks in advance

Terry Lennox
  • 29,471
  • 5
  • 28
  • 40
Somnath Rokade
  • 655
  • 1
  • 9
  • 27

1 Answers1

1

If you use a for loop, or a for...of loop then await will work as expected. You can't use foreach in this context, since it will not wait for an async function to complete.

Also, remember you can only use await in an asynchronous function.

In your case you could do something like

for(let segment of transaction.otherSegments) {
    switch (segment.segment) {
        case 'PTD': let ptdInsertRaw= await con.query('INSERT INTO `consumption-summary` SET ?', ptdInsert);
                    consumptionSummaryID= ptdInsertRaw.insertId;  

        case 'REF':
                    if(consumptionSummaryID!=0){
                      // having code related to consumptionSummaryID;
                    }
    }
}

This would also work:

for(let segmentIndex = 0; segmentIndex < transaction.otherSegments.length; segmentIndex++) {
    let segment = transaction.otherSegments[segment];
    switch (segment.segment) {
        case 'PTD': let ptdInsertRaw= await con.query('INSERT INTO `consumption-summary` SET ?', ptdInsert);
                    consumptionSummaryID= ptdInsertRaw.insertId;  

        case 'REF':
                    if(consumptionSummaryID!=0){
                      // having code related to consumptionSummaryID;
                    }
    }
}

A basic example of using a for .. of loop with await is below:

// Mock function returning promise to illustrate for .. of and await.
function writeItemToDB(item) {
    return new Promise((resolve) => setTimeout(resolve, 1000));
}

async function testWait() {
  console.log("Writing items to db..");
  let items = [...Array(5).keys()];

  for(let item of items) {
      let result = await writeItemToDB(item);
      console.log("Wrote item "  + item + " to db..");
  }
  console.log("Done.");
}

testWait();
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40