0

I am working with MySQL server, building a NodeJS server.

SomeWhere in the code I have async code that is not waiting, I believe its has something to do with the forEach function.

Is there anything wrong with my implementation of my next function:

  async addResponsesToTasks(input, response, isFromCache) {
    if (!isFromCache) {
      this.saveResponseToCache(input, response);
    }

    console.log("===7===");
    await response.forEach(async (pokemon) => {
      console.log("===8===", pokemon);
      await this.addTaskToFile(pokemon, false);
      console.log("===13===");
    });
    return true;
  }

And this is the output shows that it is not waiting for creation and save in the DB to finish, and jump to do some other things: Prints of the output - can see 10,12,13,14,15 and only then 11

Hope you could maybe spot what I am missing.

Thanks in advance!

Avr.Nadav
  • 33
  • 1
  • 4

2 Answers2

0

What's happening here is more of a JavaScript thing than a Sequelize thing.

The await is being applied to the lines of code that follow Item.create() inside of this function, but outer functions are continuing to execute.

console.log('9')
saveTaskToDb(task)
console.log('12')

In this code, '12' is going to get logged out before your '11', because this outer code is going to continue to execute, even if the code in saveTaskToDb is awaiting the resolution of the create() method.

To solve this, you'll either need to move all of your asynchronous code into the same code block, or you'll need to return your own promise in the saveTaskToDb function, and await saveTaskToDb.

boc4life
  • 941
  • 5
  • 10
  • the thing is, that I do have await outside when calling saveTaskToDB: console.log("===9==="); await this.saveTaskToDB(task); console.log("===12==="); – Avr.Nadav Jun 23 '22 at 15:05
  • I have edited my question, I believe it falls on outer call, happening in forEach function. I feel that my implementation is ok, but somehow I think this is the one who is not waiting as it should. – Avr.Nadav Jun 23 '22 at 15:13
  • Try using a for...in loop instead of forEach. – boc4life Jun 23 '22 at 15:27
0

So Solution was not using forEach, rather using for of loop like that:

async addResponsesToTasks(input, response, isFromCache) {
  if (!isFromCache) {
    this.saveResponseToCache(input, response);
  }

  for (const pokemon of response) {
    await this.addTaskToFile(pokemon, false);
  }
  return true;
}

Based on this question: Using async/await with a forEach loop

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
Avr.Nadav
  • 33
  • 1
  • 4