【问题标题】:How to call an imported async function using node require?如何使用 node require 调用导入的异步函数?
【发布时间】:2019-11-18 09:06:02
【问题描述】:

我正在尝试使用异步函数和 Puppeteer 获取纬度和经度数据。

我希望看到我获取的纬度和经度值。但是,我收到以下错误。

const latLong = 等待 getLatLong(config);
^^^^^

SyntaxError: await 仅在异步函数中有效

节点.js
const getLatLong = require('./util/latLong');
const latLong = await getLatLong(config);
latLong.js
const getLatLong = async ( city, state, ) => {
  ...
  const browser = await puppeteer.launch();
  ...
  const page = await browser.newPage();
  await page.goto( url, waitUntilLoad, );
  await page.type( placeSelector, placeString, );
  await page.click( runButtonSelector, waitUntilLoad, );
  ...
  const results = await page.evaluate( ( lat, long, ) => {
    const latitude = Promise.resolve(document.querySelector(lat).value);
    const longitude = Promise.resolve(document.querySelector(long).value);
    const out = { latitude, longitude, }
    return out;
  }, [ latitudeSelector, longitudeSelector, ] );
  ...
  await browser.close();
  return results;
}

const latLong = async ({ city, state, }) => {
  const out = await getLatLong( city, state, );
  return out;
};

module.exports.latLong = latLong;

我做错了什么?

【问题讨论】:

  • 你需要在你调用getLatLong async的地方创建函数。
  • 或者只在返回的承诺上使用.then()
  • @jfriend00:感谢您的评论。您的想法在代码中的表现如何?随时提供答案。您的想法很可能有助于扩展我对异步和承诺的理解。
  • @Mowzer - 使用.then() 似乎是你应该从有关承诺的基本教育材料中学到的东西。如果这真的是你不知道的事情,请查找并阅读一些关于使用 Promise 的教程,因为它也会以其他方式使你的编程受益。 getLatLong(config).then(latLong => { console.log(latLong);});
  • @jfriend00:问题更多的是关于在哪里使用then,而不是如何。因为有许多不同的可能性。谢谢。

标签: javascript node.js asynchronous require


【解决方案1】:

正如错误消息所说,await 只能在async 函数中使用。将其包裹在async 中,例如这样:

const getLatLong = require('./util/latLong');

(async () => {
    const latLong = await getLatLong(config);
    console.log(latLong);
})();

但请记住,所有依赖于latLong 结果的代码也必须在async 包装器中。

【讨论】:

    猜你喜欢
    • 2017-09-28
    • 2019-04-01
    • 1970-01-01
    • 2015-02-20
    • 1970-01-01
    • 2018-10-03
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    相关资源
    最近更新 更多