Http request inside a loop

前端 未结 2 559
误落风尘
误落风尘 2021-01-06 11:36

I\'m having some troubles in making a HTTP request inside a loop.

Let me explain what I have....

I make an http GET to retrieve some values and then I need t

相关标签:
2条回答
  • 2021-01-06 12:29

    Did you forget to use your looping variables i and j. The code above will keep making requests with body[0] as src and body[1] as dest for the duration of the loop provided body has length >= 2. Try using https://github.com/caolan/async#forEachOf or https://github.com/caolan/async#each for calling async functions in a loop.

    0 讨论(0)
  • 2021-01-06 12:31

    The issue here is one of Javascript scoping, and typos.

    First, you hardcoded the array indexes of body[0] and body[1]. It looks like you meant for them to be the loop variables.

    Second, an outline of your scoping problem, in simplified pseudo-Javascript:

    var requestList = [...];
    
    for(var i = 0; i < requestList.length; i++){
        var current = requestList[i];
    
        // make a request based on current or the data
        // in current. 
        request(..., function(result){
            // do something with the current variable
            current.foo = result.bar;
        });
    }
    

    All web requests are asynchronous. There used to be a way to force them to run synchronously, but it is deprecated in most major browsers. This means that the request is made, and may get a response, outside of your actual code, and then calls some sort of callback--in this case, the anonymous inner function function(result){...}.

    What this means is that that for loop continues to execute and loop while the request is being made, meaning if the request isn't fast enough, current will update and be different when the request comes back, and so will the for loop variables.


    The solution I've run into for this sort of thing is function scoping out the inner request in the for loop.

    Instead of making the new request directly inside the for loop, you move that out to its own function:

    var requestList = [...];
    
    for(var i = 0; i < requestList.length; i++){
        var current = requestList[i];
    
        GetMyResourceData(current);
    }
    
    function GetMyResourceData(current){
        request(..., function(result){
            // do something with the current variable
            current.foo = result.bar;
        });
    }
    

    Every time the GetMyResourceData function is called, a new scope is created for that function, so the current variable in that function is held when you reach the callback.

    So, that's what I'd recommend you do for your code. Move the second request outside of the for loop into its own scope.

    0 讨论(0)
提交回复
热议问题