0

I've an promise object that result from sequelize findAll, I tried to loop the data using map but it doesn't work like I need. Here the example of my code:

const list = await queueProcess.findAll({
    where: {
        id: {[Op.between]: [start, end]},
        is_active: true
    },
    attributes: ['id', 'param_value']
});

await Promise.all(
    list.map(async (e) => {
        console.log("Promise");
        const check = await checkProcess(e.id);
   })
)

this is another function from another file:

checkProcess: async (id) =>{
    console.log("Check");
}

it give me result:

Promise
Promise
Check
Check

and what I need is

Promise
Check
Promise
Check

Why does this happen? I thought that my code is appropriate, and can work asyncly.

Blackjack
  • 1,016
  • 1
  • 20
  • 51
  • 2
    The asynchronous processes run in parallell but you want to run them in sequence. To accomplish that, use a `for` or `while` loop instead of `map()` and `await` each process. That way each process will resolve before the next one is initiated. – Lennholm Mar 31 '20 at 08:08

1 Answers1

1

Each .map callback is running immediately, in parallel - each item in the list results in Promise being logged, and separately, checkProcess is called for each. The Promises here are not intrinsically connected to each other (not until they resolve, after which the Promise.all recognizes it and resolves itself).

If you want every iteration to fully resolve before the next iteration starts, use a for loop for serial processing instead of Promise.all, which is for parallel processing:

for (const e of list) {
  console.log('Promise');
  const check = await checkProcess(e.id);
}
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320