Search code examples
javascriptnode.jspostgetdelay

Need delay in between POSTs in JavaScript loop iterations


I have a json file and I am iterating over its contents and using a HTTP post request for each iteration. The POST request inserts info in a database. I need to introduce a delay either in the loop or somehow in between the POSTs. What I have now is this:

var request = require('request');

for (i = 0; i < arr.length; i++) {
    request.post(
        'http://localhost:3000/post',
        { form: { from: arr[i][0], to: arr[i][1]} },
        function (error, response, body) {
            if (!error && response.statusCode == 200) {
                console.log(body)
            }
        }
    );
}

Currently, the POST requests are called pretty much instantaneously after one another, which poses a problem for some of the DB insertion logic that requires some time in between. Does anyone have a good idea as to how to implement a delay?

Thank you


Solution

  • The problem you've got is you're mixing synchronous (loop) and asynchronous (request) operations.

    There is no mechanism for making the outer loop wait for inner, asynchronous operations to complete before continuing to the next iteration.

    Instead you could implement recursion, requiring the callback function to instigate the next iteration of the outer "loop".

    function do_post_req(arr_key) {
        request.post(
            'http://localhost:3000/post',
            { form: { from: arr[i][0], to: arr[i][1]} },
            function (error, response, body) {
                if (!error && response.statusCode == 200) {
                    console.log(body);
                    if (arr[key+1]) do_post_req(key+1); //<-- recursion
                }
            }
        );
    }
    do_post_req(0); //<-- kick things off with first array key