I am making a function that refreshes data every so often and I am having issues with the request chain that I have. The problem is that I have a for-loop running the asynch
For completeness, the way to do async things sequentially "by hand" is to use recursion:
function dothings(things, ondone){
function go(i){
if (i >= things.length) {
ondone();
} else {
dothing(things[i], function(result){
return go(i+1);
});
}
}
go(0);
}
You want the async library.
For instance,
for(var i = 0; i < listObj.result.length; i++) {
varBody.index = i;
varBody.memberID = listObj.result[i].program_member.id;
request(
...
, function () {
// Do more Stuff
});
}
Can be written like this instead:
async.forEachOf(listObj.result, function (result, i, callback) {
varBody.index = i;
varBody.memberID = result.program_member.id;
request(
...
, function () {
// Do more Stuff
// The next iteration WON'T START until callback is called
callback();
});
}, function () {
// We're done looping in this function!
});
There are lots of handy utility functions like this in async that makes working with callbacks much much easier.