Angular中处理多个承诺的正确方式

Proper way of dealing with multiple promises in Angular

本文关键字:方式 承诺 处理 Angular      更新时间:2023-09-26

在多个$http请求完成后触发函数的正确方法是什么?我有两个选择,但我不确定哪一个是正确的。请注意,在' 1 '和' 2 '完成后,都记录'done'。

首先,我只是把所有的$http请求推到一个数组,并使用$q.all(promises).then来触发最后的回调,我不记得我在哪里看到了这一点,但它似乎工作得很好(可能是因为我的localhost处理请求的速度很快):

var one = $http.get("/request/one/"),
    two = $http.get("/request/two/"),
    promises;
    one.then(function(response){
        console.log('one');
    });
    two.then(function(response){
        console.log('two');
    });
    promises = $q.all([one, two]);
    promises.then(function(){
        console.log('done');
    });

第二,我在一些教程中见过它,包括https://egghead.io/lessons/angularjs-q-all:

var one = $q.defer(),
    two = $q.defer(),
    promises;
    $http.get("/request/one/").then(function(response){
        one.resolve('one');
    });
    $http.get("/request/two/").then(function(response){
        two.resolve('two');
    });
    promises = $q.all([one.promise, two.promise]);
    promises.then(function(result){
        console.log('done');
    });

您绝对应该采用第一种方法。第二个创建了两个不必要的承诺。$http已经返回承诺,因此不需要用$q.defer()再创建两个承诺。