Q.all promise永远不会运行然后回调

时间:2017-08-19 17:35:24

标签: javascript jquery promise

我对Q.all的工作原理感到有点迷茫。 我有以下代码段(jsfiddle):

function callUrl(remoteEndPoint){
  return $.ajax({
    url: remoteEndPoint,
    method: "GET",
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function (data) {
      console.dir(data);
    },
    error: function (xhr, textStatus, errorThrown) {
            console.error("error");
    }
  });
}
Q.all([callUrl("https://httpbin.org/get"), callUrl("https://httpbin.org/undefined")]).then(function(){
    console.log("Done");
});

第一次调用callUrl将成功,第二次调用将失败(将返回错误,因为该url不存在)。 我希望Q.all执行then回调,就像ajax.always那样,但事实并非如此。

我做错了吗?

2 个答案:

答案 0 :(得分:1)

您需要链接catch方法并回调它,因为Q.all会在遇到被拒绝的承诺时返回被拒绝的承诺。

通过catch(或者您可以传递给then的可选第二个回调),您会收到有关被拒绝承诺的回复。

答案 1 :(得分:1)

404是从服务器传播到您的JS应用程序中的错误。

使用.catch

Q.all([callUrl("https://httpbin.org/get"), callUrl("https://httpbin.org/undefined")]).then(function(){
    console.log("Done");
}).catch(function(e){
    console.log("err",e);
});