Search code examples
angularjscordovaionic-frameworkngcordova

Long running callback with Angular's $q


I'm a complete novice when it comes to AngularJS although I'm trying to learn as quickly as possible. Something I cannot get my head around is if a function needs to have a long running callback.

I'm using the Ionic framework to create a Cordova phone app. One particular library that I'm using through the ngCordova module has a connect method. On a successful bluetooth connection the successCallback is called. On an unsuccessful connection the errorCallback is called. This is expected behaviour. However, this particular method should call the errorCallback should a disconnect happen at any point. However, the promise has already been resolved through the successCallback.

I did look into using the notifyCallback option however this cannot be used if the promise is fulfilled.

What is the best way to do this?


Solution

  • What I didn't realise was the error callback would be called even after the original promise had been resolved. The only difference was that the reject wasn't ever processed as the promise was fulfilled.

    The original code was:

      connect: function (address) {
        var q = $q.defer();
        $window.bluetoothSerial.connect(address, function () {
          q.resolve();
        }, function (error) {
          q.reject(error);
        });
        return q.promise;
      }
    

    The updated code is now:

      connect: function (address) {
        var q = $q.defer();
        var disconnectionPromise = $q.defer();
        var isConnected = false;
        $window.bluetoothSerial.connect(address, function () {
          isConnected = true;
          q.resolve(disconnectionPromise);
        }, function (error) {
          if(isConnected === true) {
          disconnectionPromise.reject(error);
          }
          q.reject(error);
        });
        return q.promise;
      }
    

    The usage is as in JB Nizet's answer