0

Here is my code, in wpt.runtest function i am hitting some url and getting url in response, now i will use this url in my request function, but i need to wait for sometime as it takes some time before the data is available at the url which is to be used in request module.

wpt.runTest('http://some url ',function(err, data) {
        //console.log("hello -->",err || data);

        data_url = data.data.summaryCSV;
        console.log(data_url);
        console.log('-----------');
        console.log(data_url);
        console.log('-----------');

        request({uri:data_url,method:'GET'}, function (error, response,body)  {
            console.log('----@@@@@@----');
            console.log(response.headers);
            console.log('----@@@@@@----');
            //console.log(response);
            if (error) {
                console.log('got an error' + error);
            }
            //console.log(response);
            //console.log(body);
            var data = body;
            console.log('here is the body' + body);

what i want is, there should be a time gap or pause before my request function gets executed, how can i achieve this

Siddharth Sinha
  • 512
  • 10
  • 31
  • Possible duplicate of [What do I do if I want a JavaScript version of sleep()?](http://stackoverflow.com/questions/951021/what-do-i-do-if-i-want-a-javascript-version-of-sleep) – gokul_uf Nov 03 '15 at 07:06

1 Answers1

0

Above problem can be solved by

Using settimeout

wpt.runTest('http://some url ',function(err, data) {
        //console.log("hello -->",err || data);

        data_url = data.data.summaryCSV;
        console.log(data_url);
        console.log('-----------');
        console.log(data_url);
        console.log('-----------');
        var delay = 5000;
        settimeout(function(){
             request({uri:data_url,method:'GET'}, function (error, response,body){
              // handle error and response
             }
        }, delay);
});

using Cron

This will be really helpful if you have some extended cases of this particular problem. Ex, you need to keep track of resource at various time, lets say after every hour or day. If you are expecting such cases then considering Cron will be helpful.

Steps of execution with cron:

  1. Register a cron using the cron pattern.
  2. Start the cron.
  3. When pattern evaluates to true, your supplied function will be executed. Put your implementation (making request for resource using request library) in supplied function.

Helper libraries for cron in nodejs are Lib1, Lib2.

Examples lib1, lib2

Gaurav Gupta
  • 4,228
  • 1
  • 31
  • 59