异步请求转换成循环angular.js转换成、angular、js

2023-09-13 04:57:19 作者:哑忍

我有一个数组,我需要发送数组的值由一个通过HTTP POST请求一个web服务。对于Node.js的,我使用的异步包做就是例如: async.eachSeries 做的很好,我怎么能做到这一点的角度同样的事情。 JS,我的正常异步code;

I have an array and i need to send values of array to webservice through http post request one by one . For the node.js , i'm using "async" package to do that for ex: async.eachSeries doing it well , how can i do that same thing for angular.js , my normal async code;

//this code sends all queries of array (maybe  5.000 request at same time , it is hard to process for webservice :=) ) at same time and wait for all responses. 
//it works but actually for me , responses should wait others at end of loop should work one by one 
//like async.eachSeries module!

    for (var i = 0; i < myArr.lenght; i++) {
        (function (i) {
                var data = {
                    "myQuery": myArr[i].query
                };
                $http.post("/myServiceUrl", data).success(function (result) {
                    console.log(result);
                });
        })(i);
}

两者马特方式和克里斯→答案正确上,您可以调查Chris的约异步同步在for循环的功能理解的答案。

Both Matt Way and Chris L answers Correct , you can investigate Chris's answer for understanding about async to sync functions in for loops.

推荐答案

您可以使用 $ Q 以创建通过链接的承诺一起类似的要求。例如:

You can use $q to create a similar requirement by chaining promises together. For example:

var chain = $q.when();
angular.forEach(myArr, function(item){
    chain = chain.then(function(){
        var data = {
            myQuery: item.query
        };
        return $http.post('/myServiceUrl', data).success(function(result){
            console.log(result);
        });
    });
});

// the final chain object will resolve once all the posts have completed.
chain.then(function(){
    console.log('all done!');
});

实际上你只是运行下一个诺言,一旦previous一个人完成。这里强调的事实是,每个请求会等到previous一个人完成,根据你的问题。

Essentially you are just running the next promise once the previous one has completed. Emphasis here on the fact that each request will wait until the previous one has completed, as per your question.