gpt4 book ai didi

javascript - 连接 promise ,或者一个 promise 触发另一个 promise

转载 作者:行者123 更新时间:2023-11-28 20:10:48 26 4
gpt4 key购买 nike

我正在构建一个天气应用程序,我首先必须获取用户位置,然后发出获取天气的请求。

所以我有一个 GeolocationService 和一个 WeatherService。我的 WeatherService 当前正在调用 Geolocation 服务。如何让 WeatherService 等到收到 GeolocationService 的结果后才发出 HTTP 请求?

  app.factory('GeolocationService',function($q,$window,$rootScope){        return {            getLatLon: function(){                var deferred = $q.defer();                if(!window.navigator){                    $rootScope.$apply(function(){                        deferred.reject(new Error("Geolocation not available"));                    });                } else {                    $window.navigator.geolocation.getCurrentPosition(function(position){                        $rootScope.$apply(function(){                            deferred.resolve(position);                        });                    }, function(error){                        $rootScope.$apply(function(){                            deferred.reject(error);                        });                    });                }                return deferred.promise;            }        };    });    app.factory("WeatherService", function ($q,$http,$rootScope, GeolocationService) {        return {            getWeather: function(){                var weather;                var loc = new GeolocationService.getLatLon();                 var  lat= loc.lat || 37.4568202221774,                 lon= loc.lon || -122.201366838789 ;                var units = '';                var url = 'http://api.openweathermap.org/data/2.5/forecast/daily?lat='+lat+'&lon='+lon+'&units='+units+'&callback=JSON_CALLBACK';                $http.jsonp(url)                    .success(function(data) {                        weather=data;                        return weather;                    })                    .error(function(err){                        weather=err;                        return err;                    });            }        };    });

最佳答案

您只需要在服务中使用 promise ,然后链接 promise 。例如,我有一个带有 user.company_id 的用户,如果我想获取公司名称,我必须等待用户加载。跟你的情况是一样的。

这是我的服务:

    angular.module('UserService', []) 
.factory('UserService', function($q , $http, $rootScope,$timeout) {
var currentUserPromise = null;
var currentCompanyPromise = null;
return {
getCurrentUser: function() {
if (currentUserPromise === null) {
var config = {};
config.cache = true;
config.method = "GET";
config.url = "users/get_current_user";
currentUserPromise = $http(config)
.then(function(response) {
if (typeof response.data === 'object') {
return response.data.user;
} else {
// invalid response
return $q.reject(response.data);
}
}, function(response) {
// something went wrong
return $q.reject(response.data);
});
}
return currentUserPromise;
},

getCurrentCompany: function(company_id) {
if (currentCompanyPromise === null){
var config = {};
var company = {};
company.id = company_id;
config.cache = true;
config.method = "GET";
config.url = "/companies/show";
config.params = company;
currentCompanyPromise = $http(config)
.then(function(response) {
if (typeof response.data === 'object') {
return response.data.company;
} else {
// invalid response
return $q.reject(response.data);
}

}, function(response) {
// something went wrong
return $q.reject(response.data);
});
}
return currentCompanyPromise;

}
};
});

在我的 Controller 中我这样使用:

Controller :

var promiseCurrentUser = UserService.getCurrentUser();
promiseCurrentUser.then(function(user) {
$scope.currentUser = user;
UserService.getCurrentCompany(user.company_id).then(function(company){
$scope.companyName = company.name;
});
});

Promise 的最酷之处在于它一次性解决。

希望这对您有帮助。

关于javascript - 连接 promise ,或者一个 promise 触发另一个 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19938773/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com