我将Q.all
与spread
结合使用,以便迁移在成功解析promise
:时同时执行的两个promise.then
var p1=112;
var p2=function(data){
console.log(data);
return getFormDataWithDropdown(objtype,scenario);
};
var guidRequest=processGuidRequest();
if(!Q.isPromise(guidRequest))
{
guidRequest=Q(guidRequest);
}
guidRequest.all([p1,p2])
.spread(function(geoVal,formVal){
console.log(geoVal);
console.log(formVal);
}).done();
p1
是一个value
,p2
是一个返回名为getFormDataWithDropdown的function
的函数,该函数根据promise
s的连锁集的分辨率返回promise
或value
。然而,当我运行此代码时,我会收到此错误:
Uncaught TypeError: Function.prototype.apply: Arguments list has wrong type
此功能中出现错误:
Promise.prototype.spread = function (fulfilled, rejected) {
return this.all().then(function (array) {
return fulfilled.apply(void 0, array);//error occurs here
}, rejected);
};
您的代码中存在一些严重错误(Q中也有一个小错误,因为.all
显然完成了返回非数组的任务)。
all
不进行回调。它唯一的参数要么是数组,要么是数组的promise。它可以称为静态方法:
Q.all([…])
或者作为promise(数组的promise)的方法:
Q([…]) .all()
现在,这个数组(无论它来自哪里)需要包含promise-所有的promise都将在那时等待。然而,您正在传递一个数字和一个函数。您应该用Q(p1)
将普通值包装在promise中(即使不是严格必要的),并且需要调用您的函数,以便它为您提供promise(如果它真的是一个函数的函数,那么您需要调用它两次)。
如果你想等待guidRequest
,你需要一个回调函数——不管你愿意与否。
还要注意,guidRequest
上的Q.isPromise
是不必要的,只需尝试使用Q
进行强制转换即可。
var v1=112;
function f2(data){
console.log(data);
return getFormDataWithDropdown(objtype,scenario);
};
var guidRequest = Q(processGuidRequest());
guidRequest.then(function(guid) {
var p1 = Q(v1),
p2 = f2(guid); // promises here!
return Q.all([p1, p2]);
}).spread(function(geoVal,formVal){
console.log(geoVal);
console.log(formVal);
}).done();
或者,您只需编写return [p1, p2]
,它们就会自动被spread
等待。