[英]How to resolve async error in javascript method call?
我有以下异步 javascript 代码,它在另一个文件中调用类Devices
的异步方法findDevices
。 这是一个异步方法,因为我正在该方法中的IDevices
集合中执行 mongo find。 代码如下:
let devices = await Devices.findDevices()
课程如下:
module.exports = class Devices{
static async findDevices() {
let devices = await IDevices.find({"Region" : {"$exists": false}})
loggingService.getDefaultLogger().info("Devices without region: " + devices)
return devices
}
}
当我尝试执行此代码时,出现以下错误:
let devices = await Devices.findDevices()
^^^^^
SyntaxError: await is only valid in async function
at wrapSafe (internal/modules/cjs/loader.js:979:16)
at Module._compile (internal/modules/cjs/loader.js:1027:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47
我不明白为什么会收到此错误,因为 findDevices 是一种异步方法。 如何解决此错误以及如何调用此方法。 有没有我没有考虑的另一种方法,因为我正在使用 mongo 集合IDevices
进行 mongo find ,所以我不需要该方法是 asyn 吗?
将它包装在一个异步函数中看起来像这样:
async function regionBackfill() {
let devices = await Devices.findDevices()
if(devices){
devices.forEach(device => {
await Device.updateRegion(device.SerialNumber)
});
}
}
如果是这样,我会打电话给regionBackfill()
吗? 我该怎么称呼它? 如果我只是将其称为: regionBackfill();
我犯了同样的错误
异步等待基本上是承诺的语法糖。
使用异步函数的方法是:
const example = async () => {
await otherCall();
}
你也可以这样做:
async function example() {
await otherCall();
}
对于您的具体问题,我有一个建议可以并行调用:
async function regionBackfill() {
let devices = await Devices.findDevices()
if(devices){
Promise.all([...devices.map({SerialNumber} => Device.updateRegion(SerialNumber)])
}
}
您尝试在没有异步方法的情况下调用该方法。 您可以这样调用该方法:
Devices.findDevices().then(response => devices)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.