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]()
}
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");
Promise.resolve(). await does this implicitly for you. You can simply await fn(). "If the value of the expression following the await operator is not a Promise, it's converted to a resolved Promise." - MDN awaitYou 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.
middlewares[i]is a synchronous function, so your code is doing excactly what you want it to do. If it's asynchronous, read here how to handle it.