我有一系列设备
。
对于每个设备,我想设置默认名称(“DeviceX”
- X 它是一个序列号),但其中一些可能已被使用/占用。因此,我需要发出请求来检查名称是否已存在(ifDeviceExists()
返回 true 或 false 作为响应)。如果名称已被占用,则应增加编号并再次发送请求以检查该名称(例如“Device2”)是否已存在。如果名称未被占用,则应设置该设备的名称(device.name =“Device2”)。
例如 - 占用的设备名称:“Device2”
和“Device4”
。那么新创建的设备的名称应该是:“Device1”,“Device3”,“Device5”,“Device6”
...
因此 devices
数组应该是:[{name: "Device1"}, {name: "Device3"}, {name: "Device5"}, {name: "Device6"}, ...]
这里对我来说的主要问题是检查名称是否存在是异步操作,我不知道如何处理它(在哪里发送请求以及何时订阅) 有人可以帮我吗?
最佳答案
ifDeviceExists(name: string): Observable<boolean> {
return [ 'Device2', 'Device4' ].includes(name) ? of(true) : of(false);
}
findNextDeviceName(indexWrapper: { index: number }, device: Device):
Observable<{ device: Device, name:string; index: number }> {
let currentName: string;
let currentIndex = indexWrapper.index;
return interval(0).pipe(
// send requests to check name sequentially until it returns false and filter passes event
// to first() operator which will stop interval loop, NOTE: if ifDeviceExists() allways returns true,
// there will be infinite loop
concatMap(interval => {
currentIndex = currentIndex + interval;
currentName = `Device${currentIndex}`;
return this.ifDeviceExists(currentName);
}),
filter(exists => !exists),
first(),
map(() => ({device, name: currentName, index: currentIndex})),
)
}
renameDevices(){
const devices = [{id: 101}, {id: 102}, {id: 103}, {id: 104}];
// this object keeps last index and allows to change it between concatMap iterations
const indexWrapper = {index: 1};
from(devices).pipe(
concatMap(device => this.findNextDeviceName(indexWrapper, device)),
map(result => {
indexWrapper.index = result.index + 1;
result.device.name = result.name;
return result.device;
}),
toArray()
).subscribe({
next: (devices) => {
console.log('Devices with names', devices);
}
})
}
关于javascript - 发送许多请求来检查 name 是否存在并设置 name 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72003282/