Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Wait on Array of Futures
// server/server.js
var Future = Npm.require('fibers/future');
Meteor.methods ({
testFutures: function(array) {
// var future = new Future;
// setTimeout(function() {
// future.return(array);
// }, 3000);
// return future.wait();
var futures = array.map(function(item, index){
var future = new Future;
setTimeout(function() {
future.return("Loop #" + item + " | " + index);
}, 3000);
return future;
});
return fibrousWait(futures);
}
});
// code graciously lifted from: https://github.com/goodeggs/fibrous
var fibrousWait = function() {
var futures, getResults, result;
futures = 1 <= arguments.length ? Array.prototype.slice.call(arguments, 0) : [];
getResults = function(futureOrArray) {
var i, _j, _len1, _results;
if (futureOrArray instanceof Future) {
return futureOrArray.get();
}
_results = [];
for (_j = 0, _len1 = futureOrArray.length; _j < _len1; _j++) {
i = futureOrArray[_j];
_results.push(getResults(i));
}
return _results;
};
Future.wait.apply(Future, futures);
result = getResults(futures);
if (result.length === 1) {
result = result[0];
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment