I need a loop that waits for an async call before continuing. Something like:
for ( /* ... */ ) {
someFunction(param1, praram2, function(result) {
// Okay, for cycle could continue
})
}
alert("For cycle ended");
How could I do this? Do you have any ideas?
You can use
async await
introduced in ES7:This works only if
someFunction
is returning a Promise!If
someFunction
is not returning a Promise, then you can make it return a Promise by yourself like this:Then replace this line
await someFunction(param1, param2);
byawait asynSomeFunction(param1, param2);
Please understand Promises before writing
async await
code!Here's another example which I think is more readable than others, where you wrap your async function inside a function that takes in a
done
function, the current loop index, and the result (if any) of the previous async call:Once
done()
is invoked, it triggers the next async call, again passing in the done function, current index and previous result. Once the entire loop is completed, the provided loopcallback
will be invoked.Here's a snippet you can run:
I have been using the "setTimeout(Func,0);" trick for about year. Here is some recent research i wrote up to explain how to speed it up a bit. If you just want the answer, skip to Step 4. Step 1 2 and 3 explain the reasoning and mechanics;
If you like wilsonpage's answer but are more accustomed to using async.js's syntax, here is a variation:
Demo can be found here - http://jsfiddle.net/NXTv7/8/
Given an asynchronous worker function
someFunction
that will call back a result function with aresult
argument saying whether or not the loop should continue:In order to check whether or not to end the loop, the worker function
someFunction
can forward the result function to other asynchronous operations. Also, the whole expression can be encapsulated into an asynchronous function by taking a functiondone
as callback.A promise library based solution: