首页 > 解决方案 > $q.all 不等待承诺数组返回/拒绝

问题描述

我在这里有点不知所措,因为从我在文档中阅读的内容来看,这应该可以正常工作。我有可能需要保存 3 种表格。第三个需要等待前 2 个如果它们存在,因为它需要返回它们的 id。我有以下设置:

var recProm = user.saveData(...).then(function(response)){...}
var stdProm = user.saveData(...).then(function(response)){...}

if(recProm) promise_array.push(recProm);
if(stdProm) promise_array.push(stdProm);

$q.all(promise_array).then(function(response)) {...}

但是, $q.all 永远不会等待承诺解决。我看到正确的承诺在数组中,但是当代码完成时它只是重定向回主页。

我不确定我在这里做错了什么,因为我正在向 $q.all 传递一系列承诺,就像文档要求的那样。任何帮助,将不胜感激。

更新: saveData 的代码如下:

 this.saveData= function (list, model, successMsg, errorMsg) {
       return $.ajax({
           method: 'POST',
           url: SPUrl + "/_api/web/lists/getByTitle('" + list + "')/items",
           contentType: "application/json; odata=verbose",
           headers: {
                     "X-RequestDigest": $rootScope.formRequestDigest,                       
                     "Accept": "application/json; odata=verbose"                        
                    },
           dataType: 'text json',
           data: JSON.stringify(model),
           timeout: 0
        }).then(function (data, request) {
           successMsg !== undefined && successMsg !== null ? alertify.success(successMsg) : null;
           return data.d;
       }, function (error) {
          console.log(error);
          errorMsg ? alertify.error(errorMsg + ' Error: ' + error.name + ' Status: ' + error.status) : null;
          return "error";
     });
};

标签: javascriptangularjsangular-promise

解决方案


Promise API - Angular 1.x 文档

then(successCallback, [errorCallback], [notifyCallback]) – 无论承诺何时或将被解决或拒绝,...

此方法返回一个新的承诺,它是......

在第 1-2 行,您将 .then() 方法附加到 Promise 上,从而有效地创建了一个新的 Promise。我可能错了,但由于样本没有其他“错误”,这应该是线索。


推荐阅读