gpt4 book ai didi

javascript - AngularJS $q.all 和多个 $q.defer

转载 作者:数据小太阳 更新时间:2023-10-29 04:32:24 24 4
gpt4 key购买 nike

即使我已经设法让我的代码工作,但还是有一些我不明白的地方。以下代码段功能正常:

socket.on('method', function() {
var payload = {
countrycode: '',
device: ''
};
var d1 = $q.defer();
var d2 = $q.defer();
$q.all([
geolocation.getLocation().then(function(position) {
geolocation.getCountryCode(position).then(function(countryCode){
payload.countrycode = countryCode;
d1.resolve(countryCode);
});
return d1.promise;
}),
useragent.getUserAgent().then(function(ua) {
useragent.getIcon(ua).then(function(device) {
payload.device = device;
d2.resolve(device);
});
return d2.promise
})
]).then(function(data){
console.log(data); //displays ['value1', 'value2']
})
});

有没有更好的方法来实现这一点?在我只有一个延迟变量之前,即 varvar deferred = $q.defer(); 但是这样 .then() 函数返回一个对象,结果是原来的两倍.

所以我的几个问题是:

  1. 我需要多个 $q.defer 变量吗?
  2. 以上是等待两个异步调用完成并填充有效负载对象的最佳方法吗?

最佳答案

socket.on('method', function() {
var payload = {
countrycode: '',
device: ''
};
geolocation.getLocation()
.then(function(position) {
return geolocation.getCountryCode(position);
})
.then(function(countryCode) {
payload.countrycode = countryCode;
return useragent.getUserAgent();
})
.then(function(ua) {
return useragent.getIcon(ua);
})
.then(function(device) {
payload.device = device;
console.log(data); //displays ['value1', 'value2']
});
});

read promise 链部分

关于javascript - AngularJS $q.all 和多个 $q.defer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22170648/

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