gpt4 book ai didi

angularjs - $q.all 和嵌套的 promise

转载 作者:行者123 更新时间:2023-12-04 15:22:11 25 4
gpt4 key购买 nike

有一个关于在 Angular 中使用 $q 时同步嵌套 promise 的问题。
下面的代码会确保等待整个 promise 链吗?这意味着将在 $q.all 块中等待对返回 promise 的服务的嵌套调用吗?

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 测试来确认行为。

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');
});

});

关于angularjs - $q.all 和嵌套的 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26184354/

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