2015-11-03 101 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

相關問題