承诺立即得到解决

时间:2018-08-03 18:44:52

标签: javascript asynchronous promise

我需要从多个API调用中检索数据,并通过单击UI中的按钮来聚合它们。一旦它们全部执行完毕,我就需要打印数据。我从运行for循环的函数返回一个Promise,以连续进行所有API调用。我在接收API调用结果时也正在处理它们。因此,我只在for循环之外解决了诺言。 (请注意,for循环在内部进行了一些API调用。)现在,当我调用此函数时,promise将立即得到解决,成功函数将运行,这基本上给了我空的汇总数据,这是我们所不希望的。在这种情况下,我应该在哪里/如何解决诺言?

我的代码的基本结构:

forLoopFunction(xyz)
  .then(function(){ // print aggregate data when successfull})
  .catch(function(){ // print couldn't retrieve data })


forLoopFunction(){

   return new Promise(resolve, reject){
     for(var i=0; i<...){
       api1_Call().$promise
         .then(
            api2_call().$promise
             .then(
               //work on aggregate data
            )
            .catch(reject(error))
         ).
        .catch(reject(error))
     }
     //end of for loop 
     resolve(aggregated_data);
 }
}

编辑后的代码结构:

    //$scope.requests is populated before this function call, have seen it printed

    $scope.myFunc() 
        .then(function(result){console.log(result)})
        .catch(function(error){console.log("failed")})


    $scope.myFunc = function() {
            var promiseArray = [];
            for(var i=0; i<$scope.requests.data.length; i++) {
                promiseArray.push(new Promise(function(resolve, reject) {                                                                 
                        var requests= $scope.requests.data[i];                            
                        WorkflowsService.get({id: requests.key}).$promise
                            .then(
                                function (data)  {
                                    StepsService.query({workflowId: workflowData.id}).$promise
                                        .then(
                                            function (steps)  {                                            
                                            //some variables calculation
                                            var metadata = []; //this belongs to a single work request

                                            //some more values pushed to metadata array
                                            //switch case to calculate appropriate endpoint and system id    

                                            //$.ajaxSetup({async: false});
                                            $.ajax({
                                                url: apiEndpoint + systemId,
                                                type: 'GET',
                                                success: function(resp){                                                        
                                                    compartmentId = resp.compartmentId;                                                                                                                
                                                    $.get("/api/compartments/" + compartmentId, function (resp) {
                                                       //some values pushed to metadata
                                                    });
                                            },
                                            error: function(resp) {
                                                //put dummy data to metadata array
                                            }
                                        });

                                        //construct a URL to be pushed into metadata                                                                                                                                    
                                        $scope.metadataString += metadata.join("\n");                                                                                        
                                        Promise.resolve("resolved promise");
                                 })
                                 .catch( function(error){ Promise.reject("rejected"); console.log(error) } )
                            })
                            .catch( function(error){ Promise.reject("rejected"); console.log(error) } )                            
                    });
                    promiseArray.push(promiseObject);                        
             }                
            return Promise.all(promiseArray).then(function() { return $scope.metadataString; });
}

1 个答案:

答案 0 :(得分:0)

使用api时,您应该一次完成对所有resolve通话的承诺,然后对promise.all进行承诺,这将为您提供then {{ 1}},以每个callback调用的数组形式出现。

api