如何解决javascript方法调用中的异步错误



我在另一个文件中有以下异步javascript代码,它调用类Devices的异步方法findDevices。这是一个异步方法,因为我正在该方法中的集合IDevices中进行mongo查找。代码如下:

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是一个异步方法。如何解决此错误,以及应该如何调用此方法。有没有另一种方法我没有考虑,我不需要这个方法是asyn吗?因为我正在用mongo集合IDevices进行mongo查找?

用异步函数包装它会像这样吗:

async function regionBackfill() {
let devices = await Devices.findDevices()
if(devices){
devices.forEach(device => {
await Device.updateRegion(device.SerialNumber)
});
}
}

如果是的话,我可以打电话给regionBackfill()吗?我该怎么称呼它?如果我把它称为:regionBackfill();,我会得到相同的错误

async await基本上是语法糖而非承诺。

异步函数的使用方法是:

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)

最新更新