Skip to content

Instantly share code, notes, and snippets.

@ama-ch

ama-ch/gist:a487e3347f3f26ec7d73 Secret

Last active Aug 29, 2015
Embed
What would you like to do?

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