Javascript Angular:如何链接未知数量的Promise [英] Javascript Angular: how to chain unknown number of promises

查看:47
本文介绍了Javascript Angular:如何链接未知数量的Promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写Angular.js服务来提取一些 JSON 提要.最初,服务不知道要请求哪些/多少资源.它们取决于另一个请求返回的ID.

I'm writing an Angular.js service to pull some JSON feeds. Initially, the service does not know which/how many resources to request; they are dependent on ids returned by a another request.

我很头疼,将 $ http 服务请求链接在一起.有一种常用的模式可以做到这一点吗?

I'm having a headache chaining the $http service requests together. Is there a commonly used pattern to do this?

我尝试了在另一个线程上建议的 Array.reduce 技术,但是在同步ID和请求的数据时遇到了问题.

I've tried the Array.reduce technique suggested on another thread, but had problems syncing the ids and the requested data.

这是我到目前为止所拥有的.有人有什么建议吗?

This is what I have so far. Does anyone have any suggestions?

aService.factory('dummy', function($http){
    // Dummy resources.
    var resources = [   
      'http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js',
      'http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js',
      'http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js'
    ];
    return {
        data: function(callback){

            var jquerySources = []

            var promiseChain = $http({method: 'GET', url: resources[0]});
            var l = resources.length
            for (var i = 1; i < l; i++ ){
                promiseChain.then(function(data){

                    jquerySources.push({
                        url: resources[i],
                        source: data
                    });

                    promise_chain = $http({method: 'GET', url: resources[i]});
                    if (i === l){
                        return callback(jquerySources);
                    }
               });
            }
        }
    }
});

谢谢.

推荐答案

如果您需要顺序发出请求,则可以创建一个可以用作链首的诺言.然后,您可以将$ http调用链接到该头并解决头承诺:

If you would need to do requests sequentially, you would create a promise which you could use as the head of your chain. Then, you could chain $http calls up to that head and resolve the head promise:

aService.factory('seq', function($http, $q){
    // Dummy resources.
    var resources = [   
      'http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js',
      'http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js',
      'http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js'
    ];
    var deferred = $q.defer();
    var resourcePromise = deferred.promise;
    var res = [];
    angular.forEach(resources, function(resource){
      return resourcePromise.then(function(){
        return $http({ method: 'GET', url: resource });
      }).then(function(data){
        res.push({res: resource, data : data});
      });
    });

    deferred.resolve();

    return {
        getResource: resourcePromise.then(function(){
          return res;
        })
    };
});

但是如果请求将并行-那么这将是一个更简单的解决方案.只是承诺的数组,只需调用$ q.all函数来等待解决所有承诺.

but if requests would be in parallel - then it would be simplier solution. Just array of promises and simply call $q.all function for waiting to resolve all promises.

aService.factory('par', function($http, $q){
    // Dummy resources.
    var resources = [   
      'http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js',
      'http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js',
      'http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js'
    ];
    var promises = [];
    var res = [];
    angular.forEach(resources, function(resource){
      promises.push(
        $http({ method: 'GET', url: resource }).then(
          function(data){
            res.push({res: resource, data : data});
          })
        );
    });

    return {
        getResource: $q.all(promises).then(function(){
          return res;
        })
    };
});

还要注意,在两种情况下,我们都有res数组来收集请求的结果.

Also note that in both cases we have res array for collecting results of requests.

示例示例

这篇关于Javascript Angular:如何链接未知数量的Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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