我正在尝试将类的实例推入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
装满设备,但是它是空的,我得到的只是[]
这是怎么回事?有人有解释吗?
答案 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?
}
}
}