Hi,
Sorry for the noob question, but I'm trying to wrap my head around using the futures library and I'm getting some strange behavior.
In a nutshell, I want to be able to:
1. Issue several asynchronous requests in parallel
2. When all of these are done, run a modifier on all the result sets
3. When the modifier is done, return the result
Here's something that (kind of) worked (note that of course <my local server> is a real working server url):
app.get("/futures", function(req, res){
var count = 0,
timers = [
5000,
5011,
10000
];
forEachAsync(timers, function (next, time) {
console.log('Requesting ',time, '>>>>>>>>>>>>>>>>>>>>>>>');
setTimeout(function(){
request('<my localserver went here>/?t='+time, function(){
console.log(count += 1, time);
console.log('Done! ',time, '<<<<<<<<<<<<<<<<<');
if (count == timers.length){
console.log("=============== ALL CALLBACKS DONE ==============");
res.send("All Done ==============");
}
})
}, time);
next();
}).then(function () {
console.log('Loop done ======');
});
});
But it doesn't seem very clean.
I tried to use chanify, like so:
function doAsyncRequest (time, p){
console.log('Setting timeout! ',time, '.........');
setTimeout(function(){
console.log('Requesting ',time, '>>>>>>>>>>>>>>>>>');
request('<my local server>/?t='+time, function(){
console.log('Done! ',time, '<<<<<<<<<<<<<<<<<');
p.fulfill();
})
}, time);
}
app.get("/chainify", function(req, res){
var Contacts,
providers,
modifiers,
consumers;
providers = {
all: function(params) {
var p = Futures.promise();
doAsyncRequest (5000, p);
return p.passable();
},
one: function(id, params) {
var p = Futures.promise();
doAsyncRequest (7000, p);
return p.passable();
},
two: function(id, params) {
var p = Futures.promise();
doAsyncRequest (7011, p);
return p.passable();
}
}
modifiers = {};
consumers = {
display: function (data, params) {
console.log(data, params);
res.send("All Done?");
}
};
console.log(178);
Contacts = Futures.chainify(providers, modifiers, consumers);
console.log(180,Contacts);
Contacts.all().display();
console.log(182);
}
But I get:
I'm sure I'm just doing something silly, but it feels like hitting my head against the wall. Any tips? What would be the cleanest, recommended, implementation for something basic like that?
thanks in advance,
Ronnie