[英]Javascript non-async function promise problem, how to fix it
我有 2 個 function:第一個是: readCSV
讀取 csv 文件,每行都包含一個站點名稱,對於每一行我都必須調用一個 Z2567A5EC9705EB7AC2C984033E0618 爬蟲。
第一個 function 是:
async function readCSV(){
const fileStream = fs.createReadStream('./topm.csv');
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
});
for await (const line of rl) {
var currentline=line.split(",");
var current_site = "http://www."+currentline[1];
await crawling("http://www."+currentline[1])
}
}
另一種是: crawling(web_page)
即對頁面進行爬取。
async function crawling(web_page){
try{
new Crawler().configure({depth: 1})
.crawl(web_page, function onSuccess(page) {
console.log(page.url);
});
}catch(error){
console.log("Error: "+error.message);
}
}
每個 function 都是異步的,但是當我調用readCSV
時,我注意到帶有await crawling(.....)
的行不會等待每個頁面的結束並並行執行很多頁面,這給了我一些頁面的警告:( (node:757) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 pipe listeners added to [Request]. Use emitter.setMaxListeners() to increase limit
(node:757) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 pipe listeners added to [Request]. Use emitter.setMaxListeners() to increase limit
我還注意到,對於一個有 100 行的文件(100 個 web 頁面),爬蟲只調用了 84 次......我不明白為什么
最后我嘗試在 readCSV function 中添加一個 promise,這樣:
async function readCSV(){
const fileStream = fs.createReadStream('./topm.csv');
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
});
for await (const line of rl) {
var currentline=line.split(",");
var current_site = "http://www."+currentline[1];
//await crawling("http://www."+currentline[1])
await (new Promise( resolve => {
new Crawler().configure({depth: 1})
.crawl(current_site, async (page) => {
console.log(page.url);
resolve();
});
}));
}
}
但是這樣它只適用於前 4 個站點(要編譯我需要添加這個--unhandled-rejections=strict
)
來自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await
await 運算符用於等待 Promise。
我認為您的問題是您的crawling
function 實際上並沒有返回 promise。 所以代碼await crawling("http://www."+currentline[1])
立即計算,返回crawling
的 function 的返回值,它是undefined
。
這可能是修復:
await new Crawler().configure({depth: 1})
//^^^
.crawl(web_page, function onSuccess(page) {
console.log(page.url);
});
這取決於crawl
方法返回的內容,但如果它返回 promise,那應該是正確的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.