Skip to content

Instantly share code, notes, and snippets.

@yankeyhotel
Forked from deanrad/futures_wait.js
Created April 19, 2016 15:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yankeyhotel/fc3bda3cfef773c4331f7453e7a34064 to your computer and use it in GitHub Desktop.
Save yankeyhotel/fc3bda3cfef773c4331f7453e7a34064 to your computer and use it in GitHub Desktop.
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