Skip to content
Advertisement

Promises in array forEach loop

I have an array like this:

JavaScript

Inserted are id values. Based on this ids I have to get for each one some information from the database. Basicly I get data by using following function which is located in db.js:

JavaScript

And than bascily in my main.js I use this function like this:

JavaScript

But when I would use this in an array it wouldnt work. Beginning with that I have multiple promises on the var currentpromise or that they get override by calling the getdata function every time in array forEach.
How to fix my problem to loop through the array without errors?

JavaScript

I dont think it is so important but here we have the get_data.php:

JavaScript

EDIT: dp.php

JavaScript

Hope someone can help me with this. Thanks in advance.
Filip

Advertisement

Answer

ForEach is synchronous in nature and you shouldn’t use promises or any async code inside forEach loop as it will simply iterate over array without waiting for promise to get fulfilled. You could for await...of loop instead.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement