Last active
January 27, 2016 09:15
-
-
Save IUnknown68/a02c700a6d44d106d784 to your computer and use it in GitHub Desktop.
Run fn when Promise.all on remaining arguments gets resolved.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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)); | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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