【问题标题】:Javascript/Node.js - How to properly wait for asynchronous function to return a valueJavascript/Node.js - 如何正确等待异步函数返回值
【发布时间】: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


【解决方案1】:

您可以使用异步 IIFE 或 then 处理程序。

首先是创建一个异步函数并立即调用它:

(async () => {
   // await works here
   var livetable = await myNodeJSModule.get_livetable(options)
})();

或者在结果准备好时使用then注册回调:

myNodeJSModule.get_livetable(options).then((livetable) => {
  // process the result
})

【讨论】:

    猜你喜欢
    • 2020-03-21
    • 1970-01-01
    • 2011-03-04
    • 2013-07-24
    • 2020-08-19
    • 2020-04-20
    • 2020-12-23
    • 1970-01-01
    • 2018-01-03
    相关资源
    最近更新 更多