Resolve and q.All() issue

微笑、不失礼 提交于 2020-01-25 11:00:51

问题


I am trying to resolve a method like below using ui-router

$stateProvider
        .state('abc', {
            url: 'xyz',
            templateUrl: 'templateURL',
            controller: ctrl,
            resolve:{
                data: function(someService){
                    data = someService.init();
                    return data;
                }
            }
        })

And my service code looks like this

var someObject = {
  data1: ...,
  data2: ....,
  ...
}
return{
   init: function(){
   promise1 = ...
   promise2 = ...
   promise3 = $http.get('someurl').then(function(){
   ...
   ...
   //do some manipulation with someObj
   return someObject;
   });
   $q.all(promise1 , promise2 ).then(promise3);
   }
}

When I debug the code, it is coming to line return someObject but then it is not resolving.

What am I doing wrong?


回答1:


If you want promise3 to only execute after promise1 and promise2 then try

return $q.all([promise1, promise2])
    .then(function(arrayOfData) {
        return promise3;
    });

Here is an example to illustrate the difference:

    var promise1 = $timeout(function() {
        return 'promise1Data';
    }, 1000); 
    var promise2 = $timeout(function() {
        return 'promise2Data';
    }, 2000);
    var promise3 = $timeout(function() {
        return 'promise3Data';
    }, 5000);

    // This is what you're essentially doing when your route resolves
    $q.all([promise1, promise2])
        .then(promise3)
        .then(function(data) {
            console.log(data); // You get ["promise1Data", "promise2Data"]
        });

    // This is what I think you want
    $q.all([promise1, promise2])
        .then(function(arrayOfResolvedData) {
            return promise3;
        })
        .then(function(data) {
            console.log(data); // You get promise3Data
        });



回答2:


You must pass callback functions to .then(…). Your promise3 is none.

I suspect you wanted to do

return $q.all([promise1, promise2, promise3]) 


来源:https://stackoverflow.com/questions/32000037/resolve-and-q-all-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!