如果我的项目经常使用Promise
,那么在编写函数时解决所有参数的promises是个好主意吗?例如,
function foo (arg1, arg2, arg3) {
// do stuff with arg1, arg2, arg3
}
let pArg1 = getArg1Async();
let pArg2 = pArg1.then(calcArg2Async);
let pArg3 = getArg3Async();
let p = Promise.join(pArg1, pArg2, pArg3, foo);
变为
function foo(pArg1, pArg2, pArg3) {
return Promise.join(pArg1, pArg2, pArg3, function(arg1, arg2, arg3) {
// do stuff with arg1, arg2, arg3
});
}
let pArg1 = getArg1Async();
let pArg2 = pArg1.then(calcArg2Async);
let pArg3 = getArg3Async();
let p = foo(pArg1, pArg2, pArg3);
答案 0 :(得分:1)
这通常被称为"提升"一个方法。它是一种有用且已知的技术,你可以轻松地编写一个帮助你的帮助器:
function lift(fn){
return function(){
return Promise.all.call(this, arguments).then(fn);
}
}
或现代节点"现代节点"并忽略this
:
const lift = fn => (...args) => Promise.all(args).then(fn)
可以让你这样做:
var lifted = lift(myFn);
// fn will run when the promises resolve
// and return a promise for the value.
var res = lifted(promise1, promise2);