【问题标题】:How to resolve async error in javascript method call?如何解决javascript方法调用中的异步错误?
【发布时间】:2021-06-27 02:52:58
【问题描述】:

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

将其包装在异步函数中如下所示:

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

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

【问题讨论】:

  • await 仅在异步函数中有效。您的声明 let devices = await Devices.findDevices() 在异步函数中。这就是规则。将它包装在一个异步函数中,然后调用它或使用它。
  • 错误在let devices = await Devices.findDevices(),而不是let devices = await IDevices.find({"Region" : {"$exists": false}})
  • @TusharShahi,我已经更新了我的问题。如何将它包装在异步函数中然后调用它?
  • 这能回答你的问题吗? How and when to use ‘async’ and ‘await’
  • forEach 不会尊重其中的 await。 regionBackfill() 导致错误。不要用 await 调用它。如果您这样做,那么我们又回到了最初的问题。

标签: javascript node.js mongodb asynchronous async-await


【解决方案1】:

async await 基本上是 promise 的语法糖。

async函数的使用方法是:

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)])
    }
}

【讨论】:

    【解决方案2】:

    您尝试在没有异步方法的情况下调用该方法。您可以这样调用该方法:

    Devices.findDevices().then(response => devices)
    

    【讨论】:

      猜你喜欢
      • 2015-10-22
      • 2018-12-06
      • 1970-01-01
      • 1970-01-01
      • 2021-08-04
      • 1970-01-01
      • 2018-09-04
      • 2022-11-11
      • 1970-01-01
      相关资源
      最近更新 更多