Javascript 循环响应顺序错误的异步回调

Javascript 循环响应顺序错误的异步回调,javascript,node.js,asynchronous,callback,Javascript,Node.js,Asynchronous,Callback,我在for循环中执行异步调用,我知道响应是异步的,但如何才能始终以相同的顺序获得响应。这是我的密码: setInterval(function () { callback = function (response) { var temp2 = ''; var str = ""; test = []; console.log('STATUS: ' + response.statusCode); res

我在for循环中执行异步调用,我知道响应是异步的,但如何才能始终以相同的顺序获得响应。这是我的密码:

setInterval(function () {
    callback = function (response) 
    {
        var temp2 = '';
        var str = "";
        test = [];
        console.log('STATUS: ' + response.statusCode);
        response.setEncoding('utf8');
        response.on('data', function (chunk) 
        {
            str += chunk;
        });

        response.on('end', function () 
        {
            console.log("end found");
            temp2 = JSON.parse(str);
            for (var i in temp2['build']) 
            {
                test.push(temp2['build'][i]['id']);
                var req3 = http.request({
                    host: host, // here only the domain name
                    auth: auth,
                    port: 8111,
                    path: '/httpAuth/app/rest/builds/id:' + test[i] + '/statistics/', // the rest of the url with parameters if needed
                    method: 'GET', // do GET
                    headers: { "Accept": "application/json" }
                }, callback2);
                req3.end();
            }
        });
    }

    var req4 = http.request(options4, callback);
    req4.end();


    callback2 = function (response) {

        //console.log('STATUS: ' + response.statusCode);
        //console.log('HEADERS: ' + JSON.stringify(response.headers));
        response.setEncoding('utf8');
        var str2 = "";
        response.on('data', function (chunk) {
            str2 += chunk;
        });

        response.on('end', function () {
            points.push(parseInt(JSON.parse(str2)["property"][2]["value"]));

        });
        j++;
        if (j == test.length) {
            var sumTotal = 0;
            var sumThree = 0;
            var status = '';
            for (var i in points) {
                sumTotal += points[i];
            }
            var averageTotal = parseInt(Math.round(sumTotal / points.length));
            for (var i = 0; i < 3; i++) {
                sumThree += points[i];
            }
            var averageThree = parseInt(Math.round(sumThree / 3));
            /*if(averageThree>averageTotal)
            {
                status='warning';
            }
            else
            {
                status='ok';
            }*/
             console.log('average: ' + averageThree + ' average 100 ' + averageTotal + ' status ' + status);
            //send_event('speed', {current: averageThree/*, status: status*/, last: averageTotal});
            j = 0;
            points = [];
        }
    }
}, 15 * 1000);

此输出包含100项。从这个输出中,我获取id号,并使用这个id数组发出一个新请求。这个新回调为我提供了构建持续时间,但问题在于,这是异步发生的。我得到的响应不是来自最新的构建,而是来自第一个响应。因此,我的问题是如何以正确的顺序获得这些构建速度数组。不建议在for循环中使用匿名函数

(对我来说)最好的方法是使用异步库

一个简单的例子来回答您的问题:

var objectList = [
    {"name":"Doe", "firstname":"John", "position":1},
    {"name":"Foo", "firstname":"Bar", "position":2},
    {"name":"Gates", "firstname":"Bill", "position":3},
    {"name":"Jobs", "firstname":"Steve", "position":4},
];
var arr = [];

async.each(objectList, function(person, callback) {
    arr.push(person); // async.each is asynchronous, so at the end, the order will be bad
}, function(err) {        
    async.sortBy(arr, function(p, callback) { // Reorder
        callback(err, p.position);
    }, function(err, results) {            
        callback(null, results); // Send the result
    });
});

此示例适用于您的问题。

您当前和预期的输出在这里会很有用。此外,代码的格式也会使其更易于阅读。请注意,
for..in
用于对象的属性,而不是数组迭代器(如C#或类似代码)。我看到你使用了很多,并考虑当迭代数组(或者只是一个平原<代码> for循环<代码>,而不是<代码>…..在< /代码>循环中)
var objectList = [
    {"name":"Doe", "firstname":"John", "position":1},
    {"name":"Foo", "firstname":"Bar", "position":2},
    {"name":"Gates", "firstname":"Bill", "position":3},
    {"name":"Jobs", "firstname":"Steve", "position":4},
];
var arr = [];

async.each(objectList, function(person, callback) {
    arr.push(person); // async.each is asynchronous, so at the end, the order will be bad
}, function(err) {        
    async.sortBy(arr, function(p, callback) { // Reorder
        callback(err, p.position);
    }, function(err, results) {            
        callback(null, results); // Send the result
    });
});