【发布时间】:2020-09-28 21:28:26
【问题描述】:
我无法理解 node.js 中的异步编程。我已经阅读了多篇文章,但在我自己的代码中使用 async/await 时仍然会出错。
我正在制作一个网络爬虫 node.js 模块。
这是我的 node.js 模块中的 async/await 用法示例:
async function scrape(url, ports) {
const randomPort = options.ports[Math.floor(Math.random() * options.ports.length)];
const browser = await puppeteer.launch({
args: ['--proxy-server=socks5://127.0.0.1:' + randomPort],
});
const page = await browser.newPage();
await page.setRequestInterception(true);
page.on('request', (request) => {
if (['image', 'stylesheet', 'font', 'script'].indexOf(request.resourceType()) !== -1) {
request.abort();
} else {
request.continue();
}
});
await page.goto(url);
const content = await page.content();
const livetable = parse_body(content);
setTimeout(() => {
browser.close();
}, 3000);
return livetable;
}
exports.get_livetable = async function(options) {
// code for handling the options, create the
var data = await scrape(url);
return data;
}
我如何在其他代码中使用该模块的示例
var livetable = myNodeJSModule.get_livetable(options);
console.log(livetable);
如果我这样记录数据,节点模块会返回一个空结果——它不会等待网络爬虫函数完成其工作。如何让 get_livetable 函数等待抓取函数完成执行?
感谢您的帮助
【问题讨论】:
-
问题在于
exports.get_livetable本身是异步的,这意味着您也必须等待它。我建议改用then,如下所示:myNodeJSModule.get_livetable(options).then(function(livetable) {/*Do something...*/ console.log(livetable);}) -
请发布抓取方法的实现,因为它可能是罪魁祸首。
-
var livetable = await myNodeJSModule.get_livetable(options) -
我包含了scrape方法的实现。我不能使用 await myNodeJSModule,因为它不在 await 函数中。
-
@lukasrajnoha 你必须把它放一个。或者使用
.then(livetable => { … })而不是await。
标签: javascript node.js asynchronous async-await node-modules