如何使用节点require调用导入的异步函数?

问题描述 投票:0回答:1

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

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

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

SyntaxError:等待仅在异步功能中有效

node.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;

我在做什么错?

javascript node.js asynchronous require
1个回答
0
投票

如错误消息所述,await仅可用于async功能。将其包装在async中,例如:

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

(async () => {
    const latLong = await getLatLong(config);
    console.log(latLong);
})();
© www.soinside.com 2019 - 2024. All rights reserved.