Skip to content

Instantly share code, notes, and snippets.

@ama-ch
Last active August 29, 2015 14:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ama-ch/a487e3347f3f26ec7d73 to your computer and use it in GitHub Desktop.
Save ama-ch/a487e3347f3f26ec7d73 to your computer and use it in GitHub Desktop.

Promiseのキャンセル

bluebirdの例

https://github.com/petkaantonov/bluebird/blob/master/API.md#cancellation

http://jsbin.com/dadala/1/edit?html,js,output

function a(value) {
  return Promise.resolve(value);
}

function b() {
  return Promise.resolve('b');
}

function c() {
  return Promise.resolve('c');
}

var p = a(null).then(function(value) {
  console.log(value);
  if (value === null) {
    return p.cancel();
  }
  return b();
}).then(function(value) {
  console.log(value);
  return c();
}).then(function(value) {
  console.log(value);
}).cancellable().catch(Promise.CancellationError, function(error) {
  console.log('cancelled');
});

Closure Libraryの例

https://github.com/google/closure-library/blob/master/closure/goog/promise/promise.js

http://jsbin.com/hurobo/1/edit?html,js,output

function a(value) {
  return goog.Promise.resolve(value);
}

function b() {
  return goog.Promise.resolve('b');
}

function c() {
  return goog.Promise.resolve('c');
}
  
var p = a(null).then(function(value) {
  console.log(value);
  if (value === null) {
    return p.cancel();
  }
  return b();
}).then(function(value) {
  console.log(value);
  return c();
}).then(function(value) {
  console.log(value);
}).thenCatch(function(error) {
  if (error instanceof goog.Promise.CancellationError) {
    console.log('cancelled');
  }
});

所感

  • キャンセルというかエラーハンドリング
  • p.cancel()throw new Promise.CancellationError()とも書ける(pの参照がない時はこうなる)
  • errorの型を見てキャンセルかどうか判定するのがつらい
  • CancellationErrorが実装依存になり標準化できない
  • Promiseのキャンセルはどうあるべき?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment