使用Q.all传播时出错

时间:2014-10-09 08:40:16

标签: javascript browser promise q

我将Q.allspread结合使用,以便在成功解决promise.then时同时执行两个promise

  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();

p1valuep2是一个函数,它返回一个名为getFormDataWithDropdown的function,它返回基于promisevalue的{​​{1}}关于一组链式promise s的解析。但是当我运行此代码时出现此错误:

  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);

};

1 个答案:

答案 0 :(得分:1)

您的代码中存在一些严重错误(Q中有点错误,因为.all显然会完成返回非数组的错误。)

all 进行回调。它唯一的参数是数组或数组的承诺。它可以作为静态方法调用:

Q.all([…])

或作为promise的方法(数组的承诺):

Q([…]) .all()

现在,这个数组(无论它来自哪里)需要包含承诺 - 所有等待的承诺。然而,你传递了一个数字和一个函数。你应该使用Q(p1)将普通值包装在一个承诺中(即使没有严格要求),并且需要调用你的函数以便它给你许诺(如果它真的是你所说的函​​数的函数,你需要两次打电话。)

如果你想等待guidRequest,你需要一个回调函数 - 如果你想要或不想。

另请注意Q.isPromise上的guidRequest是不必要的,只需尝试使用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会自动等待它们。