Promise 题目

20 阅读1分钟
const promise = new Promise((resolve, reject) => {
    setTimeout(() => {
        console.log("1");
        resolve('2');
    }, 1000)
});

promise.then(res => {
    console.log(res);
});
promise.then(res => {
    console.log(res);
});

手写一个promise

const myPromise = function(excutor) {
    let self = this;
    // 存储状态
    self.status = 'pending';
    // 存储成功调用的值
    self.value = null;
    // 存储失败的值
    self.reason = null;
    
    self.onFullfilledCallbacks = [];
    self.onRejectedCallbacks = [];
    
    function resolve(value) {
        if (self.status === 'pending') {
            self.value = value;
            self.status = 'fulfilled';
             // 发布成功回调
            self.onFullfilledCallbacks.forEach(item => item(value));
        }
    }
    
    function reject(error) {
        if (self.status === 'pending') {
            self.reason = error;
            self.status = 'rejected';
            // 发布失败回调
            self.onRejectedCallbacks.forEach(item => item(error));
        }
    }
    
    try {
      excutor(resolve, reject);  
    } catch(err) {
        reject(err);
    }
}

myPromise.prototype.then = function(onFullfilled, onRejected) {
    onFullfilled = typeof onFullfilled === 'function' ? onFullfilled : function(data) {
        resolve(data);
    };
    onRejected = typeof onRejected === 'function' ? onRejected : function(error) {
        throw error;
    }
    
    // 发布订阅这模式,订阅回调
    if(this.status === 'pending') {
        this.onFullfilledCallbacks.push(onFullfilled);
        this.onRejectedCallbacks.push(onRejected);
    }
}

const demo = new myPromise((resolve, reject) => {
    console.log('test constructor');
    setTimeout(() => {
        resolve('123')
    }, 1000)
});

demo.then(data => console.log(data));