我在Node.js中運行的程序中有一個for-loop。該函數是來自xray包的x(),我正在使用它來從網頁中抓取並接收數據,然後將該數據寫入文件。這個程序用於刮〜100頁時是成功的,但我需要刮〜10000頁。當我嘗試刮取大量頁面時,會創建這些文件,但它們不包含任何數據。我相信這個問題存在,因爲for循環在繼續下一次迭代之前不等待x()返回數據。Node.js強制等待函數完成
有沒有辦法讓節點等待x()函數完成後再繼續下一次迭代?
//takes in file of urls, 1 on each line, and splits them into an array.
//Then scrapes webpages and writes content to a file named for the pmid number that represents the study
//split urls into arrays
var fs = require('fs');
var array = fs.readFileSync('Desktop/formatted_urls.txt').toString().split("\n");
var Xray = require('x-ray');
var x = new Xray();
for(i in array){
//get unique number and url from the array to be put into the text file name
number = array[i].substring(35);
url = array[i];
//use .write function of x from xray to write the info to a file
x(url, 'css selectors').write('filepath' + number + '.txt');
}
注:有些我刮不返回任何值
承諾是非常有益的在這裏。最受歡迎的圖書館之一叫做Bluebird。 –
我同意Jared Dykstra。你想要1)擺脫循環體,並將其構造爲「承諾」。 2)在第一次調用之前,先設置一個計數器,例如'ct = array.length',3)不斷調用自己,直到計數器遞減爲0. – paulsm4