在forEach循环中分配给类变量-没有结果吗?

时间:2019-06-25 02:38:49

标签: javascript class foreach this

我正在尝试将类的实例推入forEach循环内的数组,但是由于某种原因,没有任何内容推入该数组。

该循环位于类方法内部,直到console.log为止一切正常(Device代码已经过测试并可以正常工作,Device.build()方法将其中的一些成员变量填充到内部设备)

class DeviceManager {
constructor() {
    this.deviceList = [];
}

async buildDevices() {
    const deviceNames = await this.getDeviceNames();

    deviceNames.forEach(async name => {
      const device = new Device(name);
      await device.build(); 
      console.log(device); // This outputs the device as expected!
      this.deviceList.push(device); // However, the device doesn't end up in this array?
    });
  }
...
...
}

我创建DeviceManager的实例,然后调用await DeviceManager.buildDevices()

此后,我希望deviceManager.deviceList装满设备,但是它是空的,我得到的只是[]

这是怎么回事?有人有解释吗?

1 个答案:

答案 0 :(得分:0)

由于您将“ forEach”称为异步,因此您可能过早测试了设备列表。也许也尝试await的forEach循环,以确保buildDevices函数仅在forEach循环完成之后才能解析。{p>

class DeviceManager {
  constructor() {
      this.deviceList = [];
  }

  async buildDevices() {
      const deviceNames = await this.getDeviceNames();

      // Convert to 'for' loop and await for async calls
      for (let index = 0; index < deviceNames.length; index++) {
        let name = deviceNames[index];
        const device = new Device(name);
        await device.build(); 
        console.log(device); // This outputs the device as expected!
        this.deviceList.push(device); // However, the device doesn't end up in this array?
      }
    }
}