0

I am newbie on async await approach. I built the function where async await approach is used. But somehow my sequence is break through forEach Loop

const newUser = async () => {
  try {
    let t1Data = await Users.find({ sequenceid: 1 });
    if (t1Data.length > 0) {
      let newData = t1Data[0].messagescore;
      console.log("A");
      newData.forEach(async (x, i) => {
        let updateColumn = await Users.update(
          { sequenceid: 1 },
          {
            $push: {
              messagescorebefore: {
                userid: x.userid,
                score: parseFloat(x.score.toFixed(2))
              }
            }
          }
        );
        console.log(i + " Updated");
        return updateColumn;
      });
      console.log("B");
    }
  } catch (e) {
    console.log(e);
  }
};

newUser();

By this console sequence will be like this
-> A
-> B
-> 0 Updated
-> 1 Updated

Now Desired result will be like this which I did not get:

-> A
-> 0 Updated
-> 1 Updated
-> B

May be I am doing something wrong on forEach Loop.

Guys if you know where I am wrong then please let me know. Any help is really Appreciated.

/********** Updated Logic as suggestion But still got one issue *************/

const newUser = async () => {
  try {
    let t1Data = await Users.find({ sequenceid: 1 });
    if (t1Data.length > 0) {
      let newData = t1Data[0].messagescore;
      console.log("A");
      await Promise.all(
        newData.map( async (x, i) => {
          let updateColumn = await Users.update(
           { sequenceid: 1 },
           {
             $push: {
               messagescorebefore: {
                 userid: x.userid,
                 score: parseFloat(x.score.toFixed(2))
               }
             }
           }
         );
        console.log(i + " Updated");
        return updateColumn
        })
      )
        console.log(i + " Updated");
        return updateColumn;
      });
      console.log("B");
    }
  } catch (e) {
    console.log(e);
  }
};

newUser();

In this Logic Some Times my Loop breaks under map Function. Rest all things work fine.

Under map Function I console (i), so some times it breaks the sequence..

Can anyone guide me where I am wrong.....

Ankit
  • 951
  • 1
  • 9
  • 29
  • Async should be used for a function which works asynchronously and returns a Promise. Await is needed to wait that function until the value is returned. – Sergey Oct 15 '18 at 08:39
  • Regarding your update: you didn't `await` the promise returned by `Promise.all(…)` – Bergi Oct 16 '18 at 15:05
  • Dear I forgot to write the await before Promise.all. Here I forgot to write the await. Still My issues is same – Ankit Oct 16 '18 at 15:08

1 Answers1

0

Replace forEach loop with a for loop. async/await does not work in a forEach loop. See it here.

If you want a declarative style use bluebird Promise.each

Sagar Karira
  • 669
  • 2
  • 7
  • 20