I have a foreach loop that is, well… too fast. The device I’m trying to communicate with is confused. The device sends a response to a listener (which is somewhere else and does more than that), so it’s impossible (as far as I know) to await the response somehow. So I thought I could do smt like this:
something.forEach(async item => {
//do smt
await setTimeout(() => {
console.log("czekamy czekamy")
}, 2000)
})
hoping that it could stop the loop for executing the next iteration. But it doesn’t work, obviously. Is there a way to achieve what I’m trying to achieve?
3
Answers
You have to make the forEach loop async in order to await the timeout.
Edit:
You should return create and use a Promise that resolves the timeout:
Array.forEach()
will notawait
for each item to complete.If you want to have a serial execution so the next items waits until the previous is over, you can use a
for
-loop:You should use a Promise and resolve it inside the setTimeout’s callback function. Also you can’t use
forEach
because it calls the callback immediately without waiting of resolving of the promise returned from the callback function:A more generic approach would be to create a wait promise function:
But I would try an async generator as the final solution:
Also note that you can use
await
without async in the top level of JS modules: