Meow~

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
import {readFile} from 'fs';

type Resolve<T> = (result: T) => void;
type Reject = (error: unknown) => void;

type Executor<T> = (
  resolve: Resolve<T>,
  reject: Reject
) => void;

class MyPromise<T> {
  private _thenCallBack: Resolve<T> = () => {};
  private _errorCallBack: Reject = () => {};
  constructor(executor: Executor<T>) {
    executor((data: T) => {
      this._thenCallBack(data);
    },(error) => {
      this._errorCallBack(error);
    });
    return this;
  }
  then<U>(thenCallBack: (result: T) => void): MyPromise<U> {
    this._thenCallBack = thenCallBack;
    return this as MyPromise<any>;
  }
  catch<U>(errorCallBack: (error: unknown) => void): MyPromise<U> {
    this._errorCallBack = errorCallBack;
    return this as MyPromise<any>;
  }
}

new MyPromise((resolve, reject) => {
  readFile('./src/no-file.txt', (error, data) => {
    if (error) {
      reject(error);
    } else {
      resolve(data);
    }
  });
}).then((data) => {
  console.log(data);
}).catch((error) => {
  console.log(error);
});

 

posted on 2023-05-21 11:53  喵弟  阅读(48)  评论(0编辑  收藏  举报