使用 Angular 的 $q 的长 运行 回调

Long running callback with Angular's $q

在 AngularJS 方面我完全是个新手,尽管我正在尝试尽快学习。我无法理解的是一个函数是否需要一个很长的 运行 回调。

我正在使用 Ionic 框架创建 Cordova phone 应用程序。我通过 ngCordova 模块使用的一个特定库有一个 connect 方法。在成功的蓝牙连接上, successCallback 被调用。在不成功的连接上调用 errorCallback。这是预期的行为。然而,这个特定的方法 应该 调用 errorCallback 如果断开连接发生在任何时候。但是,promise 已经通过 successCallback 解决了。

我确实考虑过使用 notifyCallback 选项,但是如果承诺得到履行,则无法使用。

最好的方法是什么?

这是我要实现的函数的文档,以便能够对此 API 使用 promises。我将把实施留作练习:

/**
 * Tries connecting using bluetooth. Returns a promise. 
 * If the connection doesn't succeed, the returned promise is rejected.
 * If the connection succeeds, the returned promise is resolved with
 * an other promise (that we will call disconnectionPromise). 
 * This disconnectionPromise is never resolved.
 * It's rejected once the connection (which has been 
 * successfully established) fails. 
 */
function connect() {
    ...
}

因此,示例用法为:

var blueToothConnection = service.connect();
blueToothConnection.then(function(disconnectionPromise) {
    console.log("connection successfully established");
    disconnectionPromise.catch(function() {
        console.log("connection lost");
    });
}).catch(function() {
    console.log("impossible to establish a connection");
});

我没有意识到的是,即使在最初的承诺已经解决之后,错误回调也会被调用。唯一的区别是拒绝在承诺履行时从未被处理过。

原代码为:

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

现在更新的代码是:

  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;
  }

用法同