LoginSignup
2
1

More than 3 years have passed since last update.

極限まで単純化したPromiseのサブセット

Posted at

例外処理等はなく、とにかくthenableにすることだけに特化したPromiseのサブセットです。あまり実用的な意味はありませんが、Promiseの内部の実装を理解する上で参考になればと思います。

const Promise = window.Promise || function Promise(executor) {
  const callbacks = [];
  let isResolved = false;
  let resolvedValue = null;
  const resolved = (value) => {
    isResolved = true;
    resolvedValue = value;
    callbacks.forEach(callback => callback(resolvedValue))
  }
  const rejected = (err) => {
    callbacks.splice(0);
    console.error(err);
  }
  executor(resolved, rejected);
  this.then = (callback) => {
    if (isResolved) {
      callback(value);
    } else {
      callbacks.push(callback);
    }
  };
}
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1