Return Observable inside Promise, how to bundle it


#1

Hi, iam working with bluetooth printer, and in my printer service, i want to create method, which checks if bluetooth is enabled and if connection to device is OK. Problem is, that one of this native function returns Promise and another one returns Observable. So i tried it like this:

  checkBTConnection(device){
    return this.bluetoothSerial.isEnabled().then(isEnabled=>{
      console.log("isEnabled",isEnabled);
      if(!isEnabled) Promise.reject(new Error("Bluetooth is off"));
      this.bluetoothSerial.connect(device.address).timeout(3000).subscribe(()=>{
        Promise.resolve();
      },err=>{
        Promise.reject(new Error("Cant connect to device"));
      });
    });
  }

It didnt work, because the promise from IsEnabled resolves as everything is ok, and it doesnt wait for connect() subscription result. So i wrap the whole thing in new Promise like this:

    return new Promise((resolve,reject)=>{
      this.bluetoothSerial.isEnabled().then(isEnabled=>{
        console.log("isEnabled",isEnabled);
        if(!isEnabled) Promise.reject(new Error("Bluetooth is off"));
        this.bluetoothSerial.connect(device.address).timeout(3000).subscribe(()=>{
          resolve();
        },err=>{
          reject(new Error("Cant connect to device"));
        });
      });
    });
  }

this works, but seems not very clean to me, and as i know, creating new Promises/Observables is generally not a best practice. Is there some more elegant way to do this, so i have method, that checks everything and returns Observable/Promise with result(OK or some Error)? And what if i have more Promises, Observables inside the first Promise?

Iam a little confused with this.


#2

I am pretty sure you can replace subscribe with toPromise().