Reputation: 1244
Lets say I've got the following code,
function someFunction(){
var i = 0;
while (i < 10){
someAsyncProcess(someField, function(err, data){
i++;
// i want the next iteration of the while loop to occur after this
}
}
}
The someAsyncProcess runs, and increments 'i'.
However, due to the async nature of JavaScript, the while loop runs thousands of times before i = 10. What if I want the while loop to run exactly 10 times. What if I want the while loop to execute the code inside only after the callback function has finished executing.
Is it possible to do this without a setTimeout function?
Please note that I am still relatively new to JavaScript so if I incorrectly used any jargon, correct me.
Upvotes: 2
Views: 1687
Reputation: 816232
while
is synchronous. You cannot make it wait until an asynchronous process is done. You cannot use a while
loop in this case.
Instead you can put your code in a function and call the function itself again if the condition is met.
Example:
function someFunction() {
var i = 0;
function step() {
if (i < 10) {
someAsyncProcess(someField, function(err, data) {
i++;
step();
});
}
}
step();
}
There are quite a few libraries out there that provide ready-made solutions for this. You might also want to look into promises in general.
Upvotes: 5
Reputation: 821
You need to use replace while loop Iteration with function recursion
function someFunction() {
var i = 0;
(function asyncWhile() {
if (i < 10) {
someAsyncProcess(someField, function(err, data) {
//You code here
i++;
asyncWhile();
});
}
})(); //auto invoke
}
Upvotes: 0
Reputation: 1753
Use node package q which will help you return promises. You can achieve the same in the following manner using q.
var q = require('q');
function someFunction(){
var promises = []
var i = 0;
while (i < 10) {
promises.push(function() {
i++;
//write code here for using current value of i
})
}
return q.all(promises);
}
You can call someFunction() as below
someFunction().then(function(arrayOfResponseFromEachPromiseFunction) {
console.log(JSON.stringify(arrayOfResponseFromEachPromiseFunction, null, 4));
}).catch(function(err){
console.log(err);
}).done();
Please rectify if you find any syntax error. Hope it helps.
Upvotes: 0