AngularJS:循环POST请求,并通过各指标到相关回应 [英] AngularJS: loop POST requests and pass each index into related response

查看:191
本文介绍了AngularJS:循环POST请求,并通过各指标到相关回应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用AngularJS执行多个HTTP POST请求,我需要创建成功完成请求的对象 - 是这样的:

I am trying to use AngularJS to execute multiple http POST requests and I need to create an object of successfully finished requests - something like this:

var params = [1, 2, 3],
    url,
    i,
    done = {};

for (i in params) {
    url = '/dir/'+ params[i];
    $http.post(url, {"some_request": "not important"}).
        success(function(response) {
            done[params[i]] = 'successful';
        });
}

我想获得一个对象,这样所有成功的要求:

I would like to get an object with all successful request like this:

done = {1: 'successful', 2: 'successful', 3: 'successful'};

但显然由于http请求的异步性,我只获得

But obviously due to asynchronous nature of http requests I only get

done = {3: 'successful'};

因为当HTTP请求返回响应,环路已完成,并在它的最后一个值。

because when the http requests are returning responses, the loop already finished and is at it's last value.

这些请求的顺序并不重要,我不希望他们链(执行异步他们应该更快)。我如何传递循环索引到这些反应?谢谢你。

Order of those requests is not important and I don't want to chain them (executing them asynchronously should be faster). How do I pass that loop index into those responses? Thank you.

推荐答案

这将这样的伎俩:

var params = [1, 2, 3],
    url,
    i,
    done = {};

for (i in params) {
    (function(p) {
        url = '/dir/'+ params[p];
        $http.post(url, {"some_request": "not important"}).
            success(function(response) {
                done[params[p]] = 'successful';
            });
    })(i);
}

另一种选择是闭合

Another option is closure.

这篇关于AngularJS:循环POST请求,并通过各指标到相关回应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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