Davydoff
Davydoff

Reputation: 75

How to wait function to finish in for loop js?

I have a for-loop that iterates through functions and I want this loop to wait untill function is finished to get to the next function. How do I do that?

middlewares = []

for (let i in middlewares) {
    middlewares[i]()
}

Upvotes: 1

Views: 144

Answers (3)

Olivier Boissé
Olivier Boissé

Reputation: 18173

The following solution will work if the middlewares functions return a promise when they are asynchronous

async function loop(middlewares) {
   for (let fn of middlewares) {
     await fn();
   }
}

loop(middlewares)
  .then(() => console.log("finished");

Upvotes: 3

Kavelin
Kavelin

Reputation: 444

You could make the middlewares functions async functions. This makes it easier to wait until the function is finished and then move on to the next one. To make an async function is easy: async function(...) {...}. Read about them here.

Upvotes: 0

sunknudsen
sunknudsen

Reputation: 7320

You can’t as for loops are synchronous. I recommend using async for that.

Upvotes: 1

Related Questions