2015-11-03 106 views
0

这里是我的代码,在wpt.runtest函数中,我点击了一些url并获得了url的响应,现在我将在我的请求函数中使用这个url,但是我需要等待一段时间,因为需要一段时间才能在请求模块中使用的url上提供数据。如何在nodejs中执行两个函数之间等待

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('[email protected]@@@@@----'); 
 
      console.log(response.headers); 
 
      console.log('[email protected]@@@@@----'); 
 
      //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);

我想是,应该有一个时间上的差距还是被执行了我的请求函数之前暂停,我怎么能做到这一点

+0

的可能的复制[我该怎么办,如果我想睡觉的JavaScript版本()?](http://stackoverflow.com/questions/951021/what-do-i-做-IF-我想学一,JavaScript的版本的睡眠) –

回答

0

上述问题可以通过

来解决

使用的setTimeout使用cron

这将是真正有用的,如果你有这方面的问题的一些扩展的情况下

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); 
}); 

。例如,你需要在不同的时间跟踪资源,让每一个小时或一天后说。如果你期待这种情况,那么考虑克朗会有帮助。与执行的cron

步骤:

  1. 注册使用cron pattern一个cron。
  2. 启动cron。
  3. 当模式评估为true时,您提供的函数将被执行。将您的实现(使用request库对资源进行请求)提供给函数。

nodejs中cron的辅助函数库是Lib1,Lib2

例子lib1lib2

相关问题