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
爲什麼父然後then1
和then2
之前解決?
我該在哪裏放?我嘗試過,但它似乎並沒有工作:返回$ 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
嗯,那是確實你應該把'.then()'放在哪裏,我不知道爲什麼這不起作用 – Birchlabs
是的,沒有任何錯誤,只是事情仍然沒有按順序發生。不管怎麼樣,它實際上並不需要在第一個中嵌套這兩個promise,所以我在第一個之後再做了兩個thens(),並使用'return $ http.get(..) '謝謝你的幫助。 – jmona789