链接2异步调用(承诺API),以串行方式运行 [英] Chaining 2 asynchronous calls (promise API) to run serially

查看:107
本文介绍了链接2异步调用(承诺API),以串行方式运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是类似的问题,我发布<一个href=\"http://stackoverflow.com/questions/16307652/promise-api-combining-results-of-2-asynchronous-call\">today,但需要串行链接的请求。我有两个异步请求,其中第二请求需要第一的结果来发送查询。

  VAR db.get方法就会=功能(键){
    变种推迟= $ q.defer();     //发送异步REQ
    VAR REQ = ....
    req.success =函数(D){
        deferred.resolve(D)
    };
    req.failure =函数(D){
        deferred.reject(D)
    }    返回deferred.promise;
}VAR someFn =功能(ID){
    db.get方法就会(ID,ABC)
        。然后(函数(D){
            的console.log(在1)
            db.get方法就会(d.id,高清)
                。然后(函数(D){
                    的console.log(在2)
                    ð回报
                },功能(E){
                    //错误
                });
        },功能(E){
            //错误
        });    的console.log(在3)
};

我应该错误地认为它,因为我希望的console.log(在3)从来没有在成功场景打印为我以后回的console.log(在2)。但是,当我运行,在控制台中我看到这些订单

 的console.log(在1)
的console.log(在3)
的console.log(在2)

我想然后将阻塞,直到它得到的承诺响应(由get()返回)。所以,一切都在someFn串行执行。这是假设错了吗?什么是连锁两个异步操作,它使用的承诺,以串行方式运行的最佳方式。

感谢。

编辑:

我试了一下科坦建议链接Ajax调用在AngularJs 的。

  VAR someFn =功能(ID){
            db.get方法就会(ID,ABC)
                。然后(函数(D){
                    的console.log(在1)
                    返回db.get方法就会(d.id,高清)
                })。然后(函数(D){
                    的console.log(在2)
                    ð回报
                },功能(E){
                    //错误
                    返回null;
                })。然后(函数(D){
                    返回D组;
        });        的console.log(在3)
    };

不过,如果我作出这样

通话

  VAR解析度= someFn(1)
的console.log(RES)///未定义

铬终端显示在2 未定义。我不知道为什么结果通过 someFn 重新调整未分配到 RES


解决方案

  

我想那么直到它得到的承诺响应会阻止


没有。在JS承诺没有透明,阻隔期货,但只是为了链条回调的格局。之前执行回调返回的承诺 - 和在3 。然后返回后的记录,但在回调之前执行。如果你收益回调,它并不真正的问题外 someFn

您会宁可使用类似于

  VAR someFn =功能(ID){
    返回db.get方法就会(ID,ABC)
      。然后(函数(D){
        的console.log(在1)
        返回db.get方法就会(d.id,DEF);
      })
      。然后(函数(D){
        的console.log(在2)
        ð回报
      },功能(E){
        //错误
      });
}
someFn()。然后(函数(D){
    的console.log(在3)
});

This is similar to a question I posted today, but needs the request chained serially. I have two asynchronous requests, where the second request needs the result of first to send the query.

var Db.get = function(key){
    var deferred = $q.defer();

     //send async req
    var req = ....
    req.success = function(d){
        deferred.resolve(d)
    };
    req.failure = function(d){
        deferred.reject(d)
    }

    return deferred.promise;
}

var someFn = function(id){
    Db.get(id, "abc")
        .then(function (d) {
            console.log("At 1")
            Db.get(d.id, "def")
                .then(function (d) {
                    console.log("At 2")
                    return d
                }, function (e) {
                    //error
                });
        }, function (e) {
            //error
        });

    console.log("At 3")
};

I should be thinking it wrongly, as I expect console.log("At 3") never to be printed in success scenario as I return after console.log("At 2"). But when I run, in the console I see these order

console.log("At 1")
console.log("At 3")
console.log("At 2")

I was thinking then would block till it get response from the promise (returned by get() ). so, everything in someFn execute serially. Is this assumption wrong? What is the best way to chain two asynchronous operation, which uses promises, to run serially.

Thanks.

EDIT:

I tried what Ketan suggested Chaining Ajax calls in AngularJs .

var someFn = function(id){
            Db.get(id, "abc")
                .then(function (d) {
                    console.log("At 1")
                    return Db.get(d.id, "def")
                }).then(function (d) {
                    console.log("At 2")
                    return d
                }, function (e) {
                    //error
                    return null;
                }).then(function (d) {
                    return d;
        });

        console.log("At 3")
    };

Still, if I make a call like

var res = someFn(1)
console.log(res) /// undefined

chrome terminal shows At 2 after undefined. I am not sure why the result retuned by someFn not assigned to res.

解决方案

I was thinking then would block till it get response from the promise

No. Promises in JS are no transparent, blocking futures, but just a pattern to chain callbacks. The promise is returned before the callback is executed - and At 3 is logged after .then returns, but before the callback executed. And if you return in the callback, it doesn't really matter to the outer someFn.

You rather would use something like

var someFn = function(id){
    return Db.get(id, "abc")
      .then(function (d) {
        console.log("At 1")
        return Db.get(d.id, "def");
      })
      .then(function (d) {
        console.log("At 2")
        return d
      }, function (e) {
        //error
      });
}
someFn().then(function(d) {
    console.log("At 3")
});

这篇关于链接2异步调用(承诺API),以串行方式运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆