2

キャンセルできるブルーバードの約束があります。キャンセルされた場合、実行中のタスクを適切に中止するためにいくつかの作業を行う必要があります。タスクは 2 つの方法でキャンセルできます。promise.cancel()またはを使用しpromise.timeout(delay)ます。

タスクがキャンセルまたはタイムアウトになったときに適切に中止できるようにするには、CancellationErrors と TimeoutErrors をキャッチする必要があります。CancellationError のキャッチは機能しますが、何らかの理由で TimeoutError をキャッチできません。

var Promise = require('bluebird');

function task() {
  return new Promise(function (resolve, reject) {
        // ... a long running task ...
      })
      .cancellable()
      .catch(Promise.CancellationError, function(error) {
        // ... must neatly abort the task ...
        console.log('Task cancelled', error);
      })
      .catch(Promise.TimeoutError, function(error) {
        // ... must neatly abort the task ...
        console.log('Task timed out', error);
      });
}

var promise = task();

//promise.cancel(); // this works fine, CancellationError is caught

promise.timeout(1000); // PROBLEM: this TimeoutError isn't caught!

タイムアウトが設定される前にタイムアウト エラーをキャッチするにはどうすればよいですか?

4

1 に答える 1

5

プロミスをキャンセルすると、まだキャンセル可能な親が見つかっている限り、キャンセルは最初にその親にバブルされます。これは、子にのみ伝播する通常の拒否とは大きく異なります。

.timeout単純な通常の拒否を行い、キャンセルを行わないため、このようにすることはできません。

遅延後にキャンセルすることができます。

var promise = task();
Promise.delay(1000).then(function() { promise.cancel(); });

またはタスク関数でタイムアウトを設定します。

var promise = task(1000);

function task(timeout) {
  return new Promise(function (resolve, reject) {
        // ... a long running task ...
      })
      .timeout(timeout)
      .cancellable()
      .catch(Promise.CancellationError, function(error) {
        // ... must neatly abort the task ...
        console.log('Task cancelled', error);
      })
      .catch(Promise.TimeoutError, function(error) {
        // ... must neatly abort the task ...
        console.log('Task timed out', error);
      });
}

次のようなメソッドを作成することもできます。

Promise.prototype.cancelAfter = function(ms) {
  var self = this;
  setTimeout(function() {
    self.cancel();
  }, ms);
  return this;
};

それで

function task() {
  return new Promise(function (resolve, reject) {
        // ... a long running task ...
      })
      .cancellable()
      .catch(Promise.CancellationError, function(error) {
        // ... must neatly abort the task ...
        console.log('Task cancelled', error);
      })
}

var promise = task();

// Since it's a cancellation, it will propagate upwards so you can
// clean up in the task function
promise.cancelAfter(1000);
于 2014-05-08T10:02:59.717 に答える