この解答例はChatGPTによって生成されています,正しいかは自己判断で。

BFE.devでのAI解答例 - JavaScript コーディング問題
67. Promiseを実装する

以下は、文字列を受け取ってその文字列を大文字にするMyPromiseを実装するサンプルコードです。これを参考に、上記のスペックを満たすMyPromiseを実装してください。

class MyPromise {
  constructor(executor) {
    this.callbacks = [];
    this.onCatch = null;
    this.isPending = true;

    const resolve = (value) => {
      if (!this.isPending) return;

      this.isPending = false;
      this.callbacks.forEach((callback) => {
        value = callback(value);
      });
    };

    const reject = (error) => {
      if (!this.isPending) return;

      this.isPending = false;

      if (this.onCatch) {
        this.onCatch(error);
      } else {
        throw error;
      }
    };

    try {
      executor(resolve, reject);
    } catch (error) {
      reject(error);
    }
  }

  then(onFulfilled) {
    const promise = new MyPromise((resolve) => {
      this.callbacks.push((value) => {
        const newValue = onFulfilled(value);
        resolve(newValue);
        return newValue;
      });
    });
    return promise;
  }

  catch(onRejected) {
    this.onCatch = onRejected;
  }

  static resolve(value) {
    const promise = new MyPromise((resolve) => {
      resolve(value);
    });
    return promise;
  }

  static reject(error) {
    const promise = new MyPromise((resolve, reject) => {
      reject(error);
    });
    return promise;
  }
}

// 使用例
const promise = new MyPromise((resolve) => {
  resolve('Hello, World!');
});

promise
  .then((value) => {
    return value.toUpperCase();
  })
  .then((value) => {
    console.log(value); // HELLO, WORLD!
  });