有一个关于在 Angular 中使用 $q 时同步嵌套 Promise 的问题。
下面的代码能否确保等待整个 Promise 链?这意味着对返回承诺的服务的嵌套调用是否会在 $q.all 块中等待?
var call1 = service1.get('/someUr').then(function(){
return service2.get('/someUrl2'); //returns promise
});
var call2 = service3.get('/someUr').then(function(){
return 'hello';
});
var call3 = service4.get('/someUr').then(function(){
return service3.get('/someUrl3');//returns promise
});
$q.all(call1,call2,call3).then(function(){
console.log('All asynch operations are now completed');
});
基本上:当前代码是否有可能在所有嵌套的 Promise 得到解决之前执行 $q.all 的 then ?还是递归的?
是的,看起来凯文是正确的。我还创建了一个快速测试来确认该行为。
angular.module('myModule').controller('testController', function ($q,$scope) {
function promiseCall(data,timeout) {
var deferred = $q.defer();
setTimeout(function() {
deferred.resolve(data);
console.log(data);
}, timeout);
return deferred.promise;
}
var a = promiseCall('call1 a',1000).then(function(){
return promiseCall('call2 a',50);
});
var b = promiseCall('call1 b',500);
var c = promiseCall('call1 c',1000).then(function(){
return promiseCall('call2 c',50).then(function(){
return promiseCall('call3 c',6000);
});
});
$q.all([a,b,c]).then(function(res){
console.log('all calls are done');
});
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)