Skip to content

Instantly share code, notes, and snippets.

@IUnknown68
Last active January 27, 2016 09:15
Show Gist options
  • Save IUnknown68/a02c700a6d44d106d784 to your computer and use it in GitHub Desktop.
Save IUnknown68/a02c700a6d44d106d784 to your computer and use it in GitHub Desktop.
Run fn when Promise.all on remaining arguments gets resolved.
// Sugar.
// Instead of
//
// Promise.all([2, calculateValB(3), calculateValC(4)]).then((result) => {
// var res = calculateResult(result[0], result[1], result[2]);
// /* process result */
// });
//
// write
//
// doThen(calculateResult, 2, calculateValB(3), calculateValC(4)).then(/* process result */);
//
// or
//
// var calculate = doThen.bind(null, calculateResult);
//
// calculate(2, calcFnB(3), calcFnC(4)).then(/* process result */);
var doThen = (fn, ...args) => { return Promise.all(args).then(fn.apply.bind(fn, null)); };
// ES5:
function doWhen(fn /*, ...args*/) {
var args = Array.prototype.slice.call(argument, 1);
return Promise.all(args).then(fn.apply.bind(fn, null));
}
// defer helper
function defer() {
var deferred = {};
deferred.promise = new Promise(function(resolve, reject) {
deferred.resolve = resolve;
deferred.reject = reject;
});
return deferred;
}
// doThen
var doThen = (fn, ...args) => { return Promise.all(args).then(fn.apply.bind(fn, null)); };
// value B: sync
function calcFnB(b) {
return b + 2;
}
// value C: async
function calcFnC(c) {
var deferred = defer();
window.setTimeout(function() {
deferred.resolve(c * 2);
}, 1000);
return deferred.promise;
}
// final calculation: sync
function calcFn(a,b,c) {
return a + b + c;
}
// call: calcFn(2, B, C) when calcFnC is resolved.
doThen(calcFn, 2, calcFnB(3), calcFnC(4)).then(function(res) {
console.log('Result:', res);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment