繁体   English   中英

在Angular中处理多重承诺的正确方法

[英]Proper way of dealing with multiple promises in Angular

在多个$ http请求完成之后,触发函数的正确方法是什么? 我有2种选择,但我不确定哪一种是正确的。 请注意,在完成“一个”和“两个”之后,两个日志都已完成。

首先,我只是将所有$ http请求推到一个数组中并使用$q.all(promises).then 。然后触发最终的回调,我不记得我在哪里看到了,但是似乎工作正常(可能是因为我的本地主机处理请求的速度很快):

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已经返回了promise,因此不需要再用$q.defer()创建两个。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM