-2

I have an array of IDs, for each ID I want to make an axios.post call to create something in the database. I've done something like this.

      const promises = ids.map(async (id) =>
        await methodToCallAxiosPost(params, id)
      );
      await Promise.all(promises);
      // do stuff

now I know that Promise.all runs when all of the promises are resolved which is useful to me to update the UI, but I also want to wait for each promise inside, something like this

const data1 = await methodToCallAxiosPost(params, id1)
const data2 = await methodToCallAxiosPost(params, id2)
const data3 = await methodToCallAxiosPost(params, id3)

Because I am getting potential lock conflicts in the database and I sometimes face issues.

I have tried using for await of but it seemed similar to Promise.all or I might be using it incorrectly.

Dayman
  • 7
  • 2

1 Answers1

1

You can't. They aren't promise aware methods. Use a regular for loop instead.

const results = [];
for (let i = 0; i < ids.length; i++) {
    const result = await methodToCallAxiosPost(params, ids[i]);
    results[i] = result;
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Thank you so much, I've read that they are not aware and tried using `for await (let id of ids)` but I've realized my stupid mistake, that I should wait inside the loop not for the ids themselves as I already have them. – Dayman Dec 20 '21 at 11:55