我正在编写一个基于 promise 的方法,它接受一个参数并在下一步返回一组值。像这样:
foo(a).then(function (arr) {});
在我的方法 foo
中,我正在做这样的事情:
foo = function (a) {
...
// this will return my array
function returnArray(my_return_array) {
return RSVP.all(my_return_array).fail(console.log);
}
return requestBundleElements(a)
.then(assembleReturnArray)
.then(returnArray)
.fail(console.log);
};
我想知道是否可以通过调用 apply
传回 arguments
而不是 array
。所以我可以在我的 promise 链中添加另一个步骤并执行:
return requestBundleList(setLoadingOrder(module_list))
.then(assembleReturnArray)
.then(returnArray)
.then(returnArguments)
.fail(console.log);
与:
function returnArguments(my_result_array) {
//... "apply" something here
}
问题:
但由于我无权访问“下一个”回调方法,因此无法应用
。有什么方法可以将参数列表而不是数组发回给下一步?
最佳答案
这通常称为 .spread
将是 available natively在 ES6 中通过解构。所以目前行不通的最优解是:
foo(a).then([a,b,c] => console.log(a,b,c); /* applied array to args */);
RSVP promise 目前不支持开箱即用的 spread
,但是对于 Bluebird 或 Q,它看起来像这样:
foo(a).spread(function(a,b,c){
// array ["a", "b", "c"] was applied into three parameters.
});
如果您有兴趣,可以自己将此添加到 RSVP:
RSVP.Promise.prototype.spread = function(fn){
return this.then(function(val){ // just like then
return fn.apply(null, val); // only apply the value
});
};
这会让你做:
RSVP.Promise.resolve([1, 2, 3, 4]).spread(function(one, two, three, four){
console.log(one + two + three + four); // 10
});
关于javascript - 如何在 Javascript 的基于 promise 的设置中调用 "apply"以将参数传递给下一个 then()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24626333/