Reputation: 75
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
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
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
Reputation: 7320
You can’t as for
loops are synchronous. I recommend using async for that.
Upvotes: 1