2016-11-19 240 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