Tam*_*mas 7 javascript promise deferred angularjs
即使我设法使我的代码工作,但有一些我不明白的东西.以下代码正常运行:
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']
})
});
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来实现这一目标?在我只有一个延迟变量之前,即var var deferred = $q.defer();但是这样,.then()函数返回了一个结果加倍的对象.
所以我的几个问题是:
$q.defer变量吗?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']
});
});
Run Code Online (Sandbox Code Playgroud)
阅读承诺链条部分
您总是可以将代码分成较小的语义块,如下所示:
getCountryCode = function() {
var d = $q.defer();
geolocation.getLocation()
.then(function(position) {
return geolocation.getCountryCode(position)
})
.then(function(countryCode) {
d.resolve(countryCode);
})
.fail(function(err) {
d.reject(err);
})
return d.promise;
};
getDevice = function() {
var d = $q.defer();
useragent.getUserAgent()
.then(function(ua) {
return useragent.getIcon(ua)
})
.then(function(device) {
d.resolve(device);
})
.fail(function(err) {
d.reject(err);
});
return d.promise;
}
Run Code Online (Sandbox Code Playgroud)
这将缩短你的实际并行调用($q.all)相当多:
socket.on('method', function() {
$q.all([getCountryCode(), getDevice()])
.spread(function(countryCode, device) {
var payload = {
countryCode: countryCode,
device: device
};
// ... do something with that payload ...
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6262 次 |
| 最近记录: |