【问题标题】:Nested asynchronous calls using AngularJS使用 AngularJS 的嵌套异步调用
【发布时间】:2015-06-09 17:33:53
【问题描述】:

我正在使用 AngularJS 进行一个小项目,并且我正在进行各种异步调用,这些调用开始 变得凌乱。我知道必须有更好的方法来拨打这些电话,但我不确定如何。这就是我所拥有的:

asyncCall1(someArgument,function(asyncCall1Response) {
  // do some stuff
  asyncCall2(asyncCall1Response.someAttribute,function(asyncCall2Response) {
    // do some more stuff
    asyncCall3(asyncCall2Response.someAttribute,function(asyncCall3Response) {
        // finish doing stuff...or maybe call asyncCall4?!
    });
  });
});

使用异步调用的响应作为参数传递给另一个异步调用的正确方法是什么?

【问题讨论】:

    标签: javascript angularjs rest asynchronous callback


    【解决方案1】:

    你可以使用链式承诺,你可以在这里阅读:AngularPromises

    考虑asyncCall1 返回promise,所以我们可以这样写:

            asyncCall1.then(function(response1){
    
              // ...
              // pass data from response to other async call
              return asyncCall2(response1);
              }).then(function(response2){
    
              // ...
    
              return asyncCall3(response2);
            }).then(function(resonse3){
                // .....
    
            },
            function(error) {
    
            });
    

    'chain promises'的优点是:

    • 所有异步任务只使用一个错误回调
    • 代码看起来更清晰(没有异步金字塔)

    【讨论】:

      【解决方案2】:

      我喜欢这种方式:

      asyncCall1(arguments1)
      .then(asyncCall2)
      .then(asyncCall3)
      .then(doneFn);
      

      从 asyncCall1:s successHandler 返回的内容作为参数传递给 asyncCall2。

      示例:jsfiddle

      【讨论】:

        【解决方案3】:

        一种处理异步调用的方法可以使用 $q。它返回多个承诺。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-11-18
          • 2016-07-25
          • 1970-01-01
          • 1970-01-01
          • 2020-07-15
          • 1970-01-01
          • 1970-01-01
          • 2017-09-17
          相关资源
          最近更新 更多