如何在Angular 6中的循环中链接诺言

时间:2019-03-01 06:35:36

标签: javascript angular typescript ionic-framework promise

我正在尝试使用名为addDevice()的函数更新本地存储,它会检查密钥中是否已经有一些数据,然后将其追加到其他数据中,只需更新密钥即可。

export class DeviceService implements devicesInterface {

  devices : Array<deviceInterface> = [];  

  constructor(private storage : Storage, private http : HttpClient) { }

    addDevice(ssid : String, name : String){
      console.log("add device called "+ssid +name)
      return this.getDevices().then((res : devicesInterface) => {
        console.log("res");
        console.log(res)
        if (res) {

          this.devices = res.devices;
          console.log(res);
          this.devices.push({ ssid: ssid, name: name });
          return this.storage.set(TOTAL_DEVICES, { devices: this.devices });
        }
        else {
          console.log("not res");
          let devices_obj = { devices: [{ ssid: ssid, name: name }] };
          return this.storage.set(TOTAL_DEVICES, devices_obj);
        }
      })     
  }


  getDevices(){
    return this.storage.get(TOTAL_DEVICES)
  }
}

然后从该页面中,我调用一个API,该API可以解析为deviceInterface类型的数组。

  this.deviceService.getDevicesFromServer(this.authenticationService.getToken())
        .subscribe((res : Array<deviceInterface>) =>{
            if(res){
              this.storage.remove("TOTAL_DEVICES")
              this.devices = []
            }

            res.map(async device => {
              await this.deviceService.addDevice(device.ssid, device.name).then(res=>{
                console.log("device added..")
                this.devices.push(device)
                console.log(res)
              })
            });
          })

addDevice函数必须在链中被调用,以便下次调用它时,它获取数据并将其追加,如果该函数被异步调用,则数据将一次又一次地被覆盖。

我进行了很多搜索,但没有找到与我的问题匹配的任何相关解决方案,如何在上次调用解决后在res对象上链接迭代并调用addDevice函数。

2 个答案:

答案 0 :(得分:1)

我不认为您的map函数正在等待每次迭代完成,因此结果将被覆盖。您可以尝试:

for (const device of res) {
    await this.deviceService.addDevice(device.ssid, device.name)
    .then(res => {
            console.log("device added..")
            this.devices.push(device)
            console.log(res)
    })
}

有关更多详细信息,请参见https://stackoverflow.com/a/37576787/4553162

答案 1 :(得分:0)

您从addDevice()方法返回错误的Promise。返回设置者承诺而不是获取者承诺

addDevice(ssid : String, name : String){
  console.log("add device called "+ssid +name);

  return new Promise((resolve, reject) => {
    this.getDevices().then((res : devicesInterface) => {
      console.log("res");
      console.log(res);

      if (res) {
        this.devices = res.devices;
        console.log(res);
        this.devices.push({ ssid: ssid, name: name });
        this.storage.set(TOTAL_DEVICES, { devices: this.devices }).then(resolve).catch(reject);
      }
      else {
        console.log("not res");
        let devices_obj = { devices: [{ ssid: ssid, name: name }] };
        this.storage.set(TOTAL_DEVICES, devices_obj).then(resolve).catch(reject);
      }
    });
  });   

}