【问题标题】:Asynchronous call defer and promise chain异步调用延迟和承诺链
【发布时间】:2016-09-03 20:02:36
【问题描述】:

我坚持使用异步调用链。我尝试了谷歌,但找不到确切的答案。

要求我有方法

callApi(){
     I am calling 4 service that all are asynchronous.
     I want to chain all the asynchronous calls so that I can do  
     defer.resolve only when all request are done 
}

任何帮助都会有很大帮助。 提前致谢。

【问题讨论】:

    标签: angularjs asynchronous promise angular-promise deferred


    【解决方案1】:

    您可以使用$q.all()。它接受一个 Promise 数组并返回一个 Promise,该 Promise 将在该数组中的所有 Promise 都已解析后解析。

    例子:

    function callMultipleServices() {
        return $q.all([
            //Just some random functions returning promises...
            someAsyncService(),
            $http.get('http://google.de'),
            someOtherAsyncService()
        ]) //.then(function(resultArray) { return doSomethingWith(resultArray) }) 
    }
    

    返回的 Promise 将使用一个数组解析,其中包含您传入的 Promise 的解析值。如果您希望您的 Promise 返回以某种方式从服务结果派生的单个值,只需添加一个 .then 即可结果并以某种方式计算您的最终承诺结果(如上面的评论)

    【讨论】:

    • in .then function() 我将如何返回值。像我需要写 defer.resove(result)
    • @NaushadAhmad 只需 return 它 :-)
    猜你喜欢
    • 2012-12-17
    • 2018-11-03
    • 2016-12-08
    • 1970-01-01
    • 1970-01-01
    • 2017-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多