Angular承诺在开始时而不是在所有其他承诺之后执行

时间:2018-01-18 15:05:15

标签: javascript angularjs promise q

下面的代码不会抛出语法错误,但是在查询所有列表之前,首先执行渲染数据表上数据的THEN语句

此代码的用意是什么,有许多名称相似的sharepoint列表:Bill Cycles,Bill Cycles Archive1 .... N。

我需要查询所有这些列表以查找特定查询,并在结果变量中连接所有这些列表的结果,然后将该变量与datatables插件一起渲染,但是作为第一个语句的解释,外部.then在开始时执行。

function GetData(billCycleId, clientCode, jobCodes, engagementCode) {
    var deferred = $q.defer();
    var enhanceFunctions = [
        function(searchResultRow) {
            return spService.AddHyperLinkOnFields(searchResultRow, config.HyperLinks);
        },
        function(searchResultRow) {
            return spService.AddPresenceOnFields(searchResultRow, config.UserFields);
        },
        function(searchResultRow) {
            return spService.FormatDateFields(searchResultRow, config.DateFields, generalConfig.DateTimeFormat);
        },
        function(searchResultRow) {
            return spService.AddImageMapping(searchResultRow, config.ImageFields);
        },
        function(searchResultRow) {
            return spService.FormatNumberFields(searchResultRow, config.NumberFields);
        }
    ];

    var selectProperties = spService.TransformFieldsToSelectProperties(config.Fields); 
    var extendedSelectProperties = selectProperties.slice(); // copy array
    var hyperLinkedProperties = spService.TransformFieldsToSelectProperties(config.HyperLinks)
    extendedSelectProperties = extendedSelectProperties.concat(hyperLinkedProperties);
    var result =[];
    spService.GetAllListsFromWeb()
    .then(function (lists) {
      var listEnumerator = lists.getEnumerator();
      return $q.all(
        (function(){
          //var promises = [];
          while (listEnumerator.moveNext()) {
            var oList = listEnumerator.get_current();
            var title = oList.get_title();
            var id = oList.get_id();
            if (title.indexOf('Bill Cycles') !== -1) {
              // Get data from SP !!! this is also async and returns a promise
              //   add the promise to promises array and wait for all to finish
              //   look above in Promise.all
              //promises.push(
                GetRelatedBillCyclesFromList(
                  id, 
                  extendedSelectProperties, 
                  billCycleId, 
                  clientCode, 
                  jobCodes, 
                  engagementCode, 
                  enhanceFunctions
                )
                .then(function (data) {
                  var trimmedData = 
                    spService
                    .SpSearchQuery
                    .TrimSearchResultsToSelectProperties(
                      data, 
                      selectProperties
                    );

                    trimmedData.forEach(function(item){ // loop over source array
                        result.push(item); //append to result array
                    });
                })
              //);
            }
          }
          //return promises
        })() //IIFE returning an array of promises
      );
    })
    .then( //The promise is used to execute something after all promises are resolved, but the results are build in the result array, no need to use data
      function(data){
        //var resultadata = data;
        var dataTable = $(tableSelector).DataTable();
        dataTable.clear().rows.add(result).columns.adjust().draw(); // Resize columns based on new data sizes              
        vm.ValidDataLoaded = true;    
      }
    );

}

更新1

function GetData(billCycleId, clientCode, jobCodes, engagementCode) {
                    var deferred = $q.defer();
                    var enhanceFunctions = [
                        function(searchResultRow) {
                            return spService.AddHyperLinkOnFields(searchResultRow, config.HyperLinks);
                        },
                        function(searchResultRow) {
                            return spService.AddPresenceOnFields(searchResultRow, config.UserFields);
                        },
                        function(searchResultRow) {
                            return spService.FormatDateFields(searchResultRow, config.DateFields, generalConfig.DateTimeFormat);
                        },
                        function(searchResultRow) {
                            return spService.AddImageMapping(searchResultRow, config.ImageFields);
                        },
                        function(searchResultRow) {
                            return spService.FormatNumberFields(searchResultRow, config.NumberFields);
                        }
                    ];

                    var selectProperties = spService.TransformFieldsToSelectProperties(config.Fields); 
                    var extendedSelectProperties = selectProperties.slice(); // copy array
                    var hyperLinkedProperties = spService.TransformFieldsToSelectProperties(config.HyperLinks)
                    extendedSelectProperties = extendedSelectProperties.concat(hyperLinkedProperties);
                    var result =[];
                    spService.GetAllListsFromWeb()
                    .then(function (lists) {
                      var listEnumerator = lists.getEnumerator();
                      return $q.all(
                        (function(){
                          var promises = [];
                          while (listEnumerator.moveNext()) {
                            var oList = listEnumerator.get_current();
                            var title = oList.get_title();
                            var id = oList.get_id();
                            if (title.indexOf('Bill Cycles') !== -1) {
                              // Get data from SP !!! this is also async and returns a promise
                              //   add the promise to promises array and wait for all to finish
                              //   look above in Promise.all
                              promises.push(
                                GetRelatedBillCyclesFromList(
                                  id, 
                                  extendedSelectProperties, 
                                  billCycleId, 
                                  clientCode, 
                                  jobCodes, 
                                  engagementCode, 
                                  enhanceFunctions
                                )
                                .then(function (data) {
                                  var trimmedData = 
                                    spService
                                    .SpSearchQuery
                                    .TrimSearchResultsToSelectProperties(
                                      data, 
                                      selectProperties
                                    );

                                    trimmedData.forEach(function(item){ // loop over source array
                                        result.push(item); //append to result array
                                    });
                                })
                              );
                            }
                          }
                          //return promises
                        })() //IIFE returning an array of promises
                      );
                    })
                    .then( //The promise is used to execute something after all promises are resolved, but the results are build in the result array, no need to use data
                      function(data){
                        //var resultadata = data;
                        var dataTable = $(tableSelector).DataTable();
                        dataTable.clear().rows.add(result).columns.adjust().draw(); // Resize columns based on new data sizes              
                        vm.ValidDataLoaded = true;    
                      }
                    );

                }

1 个答案:

答案 0 :(得分:1)

问题是你的(function(){不返回promises。实际上,它什么都不返回。

但您评论的代码是正确的解决方案。你创建一个promises数组,然后使用$q.all(promises).then(function(){data}...)