0

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?

Minsaf
  • 272
  • 1
  • 5
  • 14

1 Answers1

14

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

maxspiri
  • 348
  • 2
  • 9