前端面試題 - 如何實現promise?

前端面試題 - 如何實現promise?

  • 通過構造函數生成一個promise對象,該構造函數有一個延時函數參數
  • 通過promise.then()或promise.catch()方法實現結果獲取
  • then函數和catch函數可以鏈式調用
function MyPromise(func) {
    this.status = 'pending';
    this.res = '';
    this.thenCbs = [];
    this.catchCbs = [];
    const resolve = (data) => {
        this.status = 'fulfilled';
        this.res = data;
        this.thenCbs.forEach(cb => {
            cb(this.res);
        });
    }
    const reject = (data) => {
        this.status = 'rejected';
        this.res = data;
        this.catchCbs.forEach(cb => {
            cb(this.res);
        });
    }
    this.then = function (cb) {
        if (this.status == 'pending') {
            this.thenCbs.push(cb);
        }
        if (this.status == 'fulfilled') {
            var res = cb(this.res)
        }
        return this;
    }
    this.catch = function (cb) {
        if (this.status == 'pending') {
            this.catchCbs.push(cb)
        }
        if (this.status == 'rejected') {
            var res = cb(this.res)
        }
        return this;
    }
    func(resolve, reject)
}

通俗易懂的前端面試題網站: [https://www.front-interview.com](https://www.front-interview.com)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章