javascript - Is it a good idea to resolve promises for all arguments when writing a function? -
if project uses promise
lot, idea resolve promises arguments when writing function? example,
function foo (arg1, arg2, arg3) { // stuff arg1, arg2, arg3 } let parg1 = getarg1async(); let parg2 = parg1.then(calcarg2async); let parg3 = getarg3async(); let p = promise.join(parg1, parg2, parg3, foo);
becomes
function foo(parg1, parg2, parg3) { return promise.join(parg1, parg2, parg3, function(arg1, arg2, arg3) { // stuff arg1, arg2, arg3 }); } let parg1 = getarg1async(); let parg2 = parg1.then(calcarg2async); let parg3 = getarg3async(); let p = foo(parg1, parg2, parg3);
this called "lifting" method. it's useful , known technique , can write helper you:
function lift(fn){ return function(){ return promise.all.call(this, arguments).then(fn); } }
or in "modern node" , ignoring this
:
const lift = fn => (...args) => promise.all(args).then(fn)
which let do:
var lifted = lift(myfn); // fn run when promises resolve // , return promise value. var res = lifted(promise1, promise2);
Comments
Post a Comment