2016-11-19 150 views
1

我有这个初始化函数运行,为我的应用程序设置全局依赖我使用npm包angular-global-resolve。这个包工作正常,问题是我在初始化函数中有一个带有嵌套promise的大承诺,主承诺在嵌套之前解决,这意味着应用程序第一次运行时某些事情不会被设置。我该如何解决?承诺不等待巢承诺之前解决

我的代码:
在routes.js:

globalResolveProvider.addGlobalDependenciesTo($stateProvider, { 
    getGlobalDependacies: function ($http, $rootScope, $cookies) { 
     return $http.get('/__/env.json') 
     .then(function(response) { 
     console.log('then0') 
     $rootScope.apiUrl = response.data.apiUrl; 
     $rootScope.googleMapsApiKey = response.data.googleMapsApiKey; 
     $rootScope.currentLocationLat = 40.7589; 
     $rootScope.currentLocationLng = 73.9851; 
     var hotelId = '' 
     if ($cookies.get('hotel') === undefined){ 
      console.log('if 1') 
      $http.get($rootScope.apiUrl + '/hotels') 
      .then(function(dbHotels){ 
      console.log('then1') 
      hotelId = dbHotels.data[0]._id 
      $cookies.put('hotelId', hotelId) 
      }) 
     } 
     if ($cookies.get('userId') === undefined){ 
      console.log('if 2') 
      $http.get($rootScope.apiUrl + '/users') 
      .then(function(dbUsers){ 
      console.log('then2') 
      var index = dbUsers.data.length - 1 
      var userId = dbUsers.data[index]._id 
      $cookies.put('userId', userId) 
      $rootScope.$broadcast('update-itinerary-icon') 
      }) 
     } 
     }) 
     .then(function(){ 
     console.log("parent then is resolved") 
     }) 
    } 
    }) 

的控制台登录:

then0 
if 1 
if 2 
parent then is resolved 
then1 
then2 

为什么父然后then1then2之前解决?

回答

3

当你

$http.get($rootScope.apiUrl + '/hotels') 

或者:

$http.get($rootScope.apiUrl + '/users') 

这只开始 HTTP请求。流程在父承诺中继续,而不等待嵌套的GET完成。然后父母像往常一样解决。

如果你想父等待对孩子的承诺,你必须让家长返回一个承诺

return $http.get($rootScope.apiUrl + '/hotels') 

现在,如果你想使父等待孩子的承诺,你必须返回一个承诺,其中构成多个承诺。注入$q到您的功能,并以此作为你的return语句:如果你想条件逻辑

return $q.all(
    $http.get($rootScope.apiUrl + '/hotels'), 
    $http.get($rootScope.apiUrl + '/users') 
); 

,那么你可以尝试这样的事:

return $q.all(
    ($cookies.get('hotel') === undefined) 
    ? $http.get($rootScope.apiUrl + '/hotels') 
    : $q.resolve(), 
    ($cookies.get('userId') === undefined) 
    ? $http.get($rootScope.apiUrl + '/users') 
    : $q.resolve() 
); 

这使得等待已经在没有必要工作的情况下完成承诺。

您还可以在上例中将.then()添加到$http.get()

+0

我该在哪里放?我尝试过,但它似乎并没有工作:返回$ q.all(($ cookies.get('hotel')=== undefined)?$ http.get($ rootScope.apiUrl +'/ hotels')。然后(函数(dbHotels){console.log('then1')hotelId = dbHotels.data [0] ._ id $ cookies.put('hotelId',hotelId)}):$ q.resolve() – jmona789

+0

嗯,那是确实你应该把'.then()'放在哪里,我不知道为什么这不起作用 – Birchlabs

+0

是的,没有任何错误,只是事情仍然没有按顺序发生。不管怎么样,它实际上并不需要在第一个中嵌套这两个promise,所以我在第一个之后再做了两个thens(),并使用'return $ http.get(..) '谢谢你的帮助。 – jmona789