gpt4 book ai didi

javascript - 如何使用 Node require 调用导入的异步函数?

转载 作者:行者123 更新时间:2023-12-02 22:30:42 25 4
gpt4 key购买 nike

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

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

const latLong = await getLatLong(config);
                         ^^^^^

SyntaxError: await is only valid in async function

Node .js
const getLatLong = require('./util/latLong');
const latLong = await getLatLong(config);
经纬度.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;

我做错了什么?

最佳答案

正如错误消息所示,await 只能在 async 函数中使用。将其包装在 async 中,例如如下所示:

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

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

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

关于javascript - 如何使用 Node require 调用导入的异步函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58911065/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com