1

I'm working on a task where I need to update a list todos one by one. I'm selecting a list of todos and when I click the update button, it should update the todos one by one using a forEach loop. below is the list if selected todos

selectedTodos = [ { todoID:630316783e09e69bda667e2e, userID:630316783e09e69bda63dvft3, completed:false }, { todoID:630316783e09e69bda667ssdw36, userID:988765yk6783e09e69bda667e2e, completed:false }, { todoID:630316783765gbjybda667e2e, userID:630316783e09e69vfft567742, completed:false }, ] 

I'm using a forEach loop to iterate through the list and update one by one as follow

selectedTodos.forEach(async(todo)=>{ const {data} = await axios.put(API_URL+"/todo/"+ todo.todoID,{ completed:true }) console.log(data) }) 

Here the async-await is not working inside the loop but when I update it one by one separately, it is working. It is not working only on forEach loop. I don't have an endpoint to update all at once. I need to loop through the list and update one by one. Is there any other way?

2
  • 2
    forEach with async/await in the callback NEVER does what you want - use a regular for loop (for for...in for...of - up to you) Commented Sep 12, 2022 at 4:31
  • 2
    ... or Promise.all() to run them in parallel Commented Sep 12, 2022 at 4:34

1 Answer 1

20

the easiest way to transform your code into code that works as you intend is to replace

selectedTodos.forEach(async (todo) => { 

with

await Promise.all(selectedTodos.map(async (todo) => { 

assuming you're inside an asynchronous function. How it works is selectedTodos.map returns an array of promises, and Promise.all waits for them all to be resolved before moving on. There are similar methods under the Promise class, too.

A classic

for(const todo of selectedTodos) { await actions } 

works, too. But if you like more imperative code, the first example is the same

Sign up to request clarification or add additional context in comments.

3 Comments

The for...of is not equivalent to the Promise.all as it will process them in series rather than concurrently.
good distinction, thanks
mind you Promise.all rejects as soon as one of the promises rejects.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.