javascript - 等待 1 个 promise ,然后所有 promise 都使用 $q

标签 javascript angularjs asynchronous angular-promise q

我非常熟悉 $q 的工作原理,我在 angularjs 中使用它来等待单个 promise 的解决和多个 promise 的解决 $q.all().

问题是我不确定是否可以这样做(以及它是否正常工作):我可以等待一个单一的 promise 解决,然后在我所有的 promise 都解决时运行一些代码......在各个 promise 的成功回调完成后...例如:

var promises = [];
for(i=1, i<5, i++){
    var singlePromise = SomeSevice.getData();
    promises.push(singlePromise);
    singlePromise.then(function(data){
         console.log("This specific promise resolved");
    });
}


// note: its important that this runs AFTER the code inside the success 
//  callback of the single promise runs ....
$q.all(promises).then(function(data){
    console.log("ALL PROMISES NOW RESOLVED"); // this code runs when all promises also resolved
});

我的问题是,这是否像我想的那样工作,或者是否存在一些奇怪的异步、不确定的结果风险?

最佳答案

调用 then 也会返回一个 promise 。然后你可以将它传递给你的数组而不是原来的 promise 。这样你的 $q.all 将在你所有的 then 被执行后运行。

var promises = [];
for(i=1, i<5, i++){
    // singlePromise - this is now a new promise from the resulting then
    var singlePromise = SomeSevice.getData().then(function(data){
         console.log("This specific promise resolved");
    });
    promises.push(singlePromise);
}

$q.all(promises).then(function(data){
    console.log("ALL PROMISES NOW RESOLVED");
});

关于javascript - 等待 1 个 promise ,然后所有 promise 都使用 $q,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42091078/

相关文章:

javascript - angularjs 状态提供者在 url 中使用除 id 之外的其他值

javascript - AngularJS - ng-click 不会触发我的 Controller 功能

javascript - 在angularjs中链接资源

javascript - 自定义管道未正确导入

javascript - HERE map 信息气泡无法使用 React 正确呈现

javascript - 在 html 表中动态渲染非结构化 JSON 数据

javascript - 动态 ng-init 变量 - Angularjs

javascript - 将 ng-style 与 switch 语句一起使用 - Angular JS

javascript - Nodejs - SolrClient,如何等待响应

c - ALSA PCM 回调有什么限制?