Reading qrcode with Ionic4: How to retrieve the value read from an asynchronous service provider

Hi,
I’d like to read the text of a QR code from a page, using a service provider that manages the scan features. Really I only have to get a number from this QR Code, but I have a function that does this job (getIdFromMessage) and it is working.

I don’t know how to retrieve the value read in the service provider because the method used to scan the QR code is asynchronous.
I thought to use a callback that sets in the page the text read from the service provider, so I’ have a page with this code:

// callback to set the deviceId property of the page
  public setDeviceId(deviceId) {
    alert('@@@ setDeviceId:' + deviceId);
    this.deviceId = deviceId;
  }

// the action that calls the services provider
  actionScanQrCode() {
    console.log('actionScanQrCode');
    // Passing a callback to the qrcode reader
    this.qrcodeManager.readScooterIdFromBarcode(this.setDeviceId);
  }

And a service provider with this code:

// the function that reads the QRCode
    readScooterIdFromBarcode(callback) {
      this.barcodeScanner
        .scan()
        .then(barcodeData => {
         let barcodeText: string;
          barcodeText = barcodeData.text;
          let deviceId: number;
          deviceId = Number(this.getIdFromMessage(barcodeText));:
          alert("@@@ deviceId: ", deviceId);
          callback(deviceId);
....

When I read the barcode, the function setDeviceId prints the right number, but after I have the error
TypeError: Cannot set property ‘device’ of undefined”.

So the callback isn’t working.
Is it the right way to retrieve the read value from an asynchronous function?

Thank you very much

cld

I’ve solved using a Promise not a callback.

  actionScanQrCode() {
    this.qrcodeManager.readScooterIdFromBarcode()
      .then(result => {
        this.deviceId = result;
      });
  }

where:

  readScooterIdFromBarcode() {
      return this.barcodeScanner
          .scan()
          .then(barcodeData => {
            let barcodeText: string;
            barcodeText = barcodeData.text;
            return Number(this.getIdFromMessage(barcodeText)) || 0;
          })
          .catch(err => {
            console.log('Error', err);
            return 1;
          });
    }

barcodeScanner returns a Promise so I use the “then” branch to change the value of the property “deviceId” of the caller.

cld