【发布时间】:2017-04-02 23:09:24
【问题描述】:
我有这个初始化函数来为我的应用程序设置全局依赖关系,我正在使用 npm 包angular-global-resolve。该程序包运行良好,问题是我在初始化函数中有一个带有嵌套承诺的大承诺,并且主要承诺在嵌套承诺之前解决,这意味着某些事情在应用程序第一次运行时没有设置。我该如何解决这个问题?
我的代码:
在 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 之前解决?
【问题讨论】:
标签: javascript angularjs http promise angular-promise