1

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]()
}
4
  • 1
    are the middlewares functions asynchronous or synchronous ? Commented Aug 23, 2019 at 17:18
  • 1
    if 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. Commented Aug 23, 2019 at 17:21
  • 1
    We're gonna need more of an example. This code doesn't do anything. If they're async you can chain them with promises. Commented Aug 23, 2019 at 17:23
  • Middlewares functions can be synchronous and asynchronous. Commented Aug 23, 2019 at 17:27

3 Answers 3

3

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");
Sign up to request clarification or add additional context in comments.

1 Comment

You don't even have to wrap it in 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 await
1

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.