How to slow down the code?

时间:2016-07-11 20:22:30

标签: javascript asynchronous

Another problem... I have 2 functions :

function(data, callback){              //F1
            var URL = 'url';
            request(URL, function(err, response, body) {
                if(response.statusCode == 200){
                    var json = JSON.parse(body);
                    var chid = [];
                        for(var i = 0; i < json['champions'].length;i++){
                        chid.push(json['champions'][i].id);
                    }
                    data.rotation = chid;
                    free = chid;
                    callback(null, data);
            }

        });
    },
    function(data, callback) {        //f2
        for (var r=0; r<10; r++){
            var URL = 'url';
            request(URL,function(err, response, body) {
                if(response.statusCode == 200){
                    var json = JSON.parse(body);

                    x.push(json.name);
                    data.rot = x;
                }   
            })
        }
        callback(null, data);
    },

With F1 everything is ok. If I call console.log(free) or console.log(data.rotation) I got the array I want.

Function 2 is a bit problematic. Data is not avaible outside the for-loop. If I call console.log(data.rot) or console.log(x) outside the loop, it says it's undefined, so I can't get it with handlebars. I have no idea if it's all about the callback(null, data) position or about the for-loop. I can't handle it alone.

How to get access to data outside of the for-loop? Probably callback is being called faster than all requests are done. How to slow it down and make it working?

2 个答案:

答案 0 :(得分:1)

To add some clarity to what Pointy said in comments, when the for loop executes the request, the inner function is called when the data returns. The for loop will complete, and then fire the callback, whether the data from the async request has returned or not, so the data will very likely not make it back before the callback gets called. In other words, it's a race condition that will almost always lose.

答案 1 :(得分:0)

X如上所述。这段代码运作良好。

function(data, callback) {        //f2
for (var r=0, dataRx=0; r<10; r++){
    var URL = 'url';
    request(URL,function(err, response, body) {
        if(response.statusCode == 200){
            var json = JSON.parse(body);

            x.push(json.name);
            data.rot = x;
        }
        dataRx++;
        if(dataRx === 10) callback(null, data);
    })
}

},