如何使用节点要求调用导入的异步函数?
How to call an imported async function using node require?
我正在尝试使用异步函数和 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);
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;
我做错了什么?
正如错误信息所说,await
只能在async
函数中使用。将其包裹在 async
中,例如这样:
const getLatLong = require('./util/latLong');
(async () => {
const latLong = await getLatLong(config);
console.log(latLong);
})();
但请记住,所有依赖于 latLong
结果的代码也必须在 async
包装器中。
我正在尝试使用异步函数和 Puppeteer 获取纬度和经度数据。
我希望看到我获取的纬度和经度值。但是,我收到以下错误。
node.jsconst latLong = await getLatLong(config);
^^^^^SyntaxError: await is only valid in async function
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;
我做错了什么?
正如错误信息所说,await
只能在async
函数中使用。将其包裹在 async
中,例如这样:
const getLatLong = require('./util/latLong');
(async () => {
const latLong = await getLatLong(config);
console.log(latLong);
})();
但请记住,所有依赖于 latLong
结果的代码也必须在 async
包装器中。