Resolve and q.All() issue

2019-09-05 02:06发布

问题:

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])