Home > database >  NodeJS await inside forEach function
NodeJS await inside forEach function

Time:06-24

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!

CodePudding user response:

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.

CodePudding user response:

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 that thread: enter link description here

  • Related