es6 手写 promise 原理(简单实现)

2020-05-15  本文已影响0人  alokka
实现:
const PENDING = 'PENDING';
const RESOLVE = 'RESOLVE';
const REJECTED = 'REJECTED';

class Promise {
    constructor(executor) {
        this.state = PENDING;
        this.value = undefined;
        this.reason = undefined;
        this.onResolvedCallbacks = [];
        this.onRejectedCallbacks = [];
        let resolve = (value) => {
            if (this.state === PENDING) {
                this.state = RESOLVE;
                this.value = value;
                this.onResolvedCallbacks.forEach(fn => fn());
            }
        }
        let reject = (reason) => {
            if (this.state === PENDING) {
                this.state = REJECTED;
                this.reason = reason;
                this.onRejectedCallbacks.forEach(fn => fn());
            }
        }
        try {
            executor(resolve, reject)
        } catch(e) {
            reject(e)
        }
    }

    then(onFulfilled, onRejected) {

        if (this.state === RESOLVE) {
          onFulfilled(this.value)
        }
        if (this.state === REJECTED) {
          onRejected(this.reason)
        }
        if (this.state === PENDING) {
          this.onResolvedCallbacks.push(() => {
            // TODO...
            onFulfilled(this.value)
          })
          this.onRejectedCallbacks.push(() => {
            // TODO...
            onRejected(this.reason)
          })
        }
        
      }
}

module.exports = Promise;
调用:
let p = new Promise((resolve, reject) => {
    setTimeout(() => {
    resolve('value');
},1000)
}).then((success) => {
        console.log(success);
},(err) => {
    console.log(err);
})
上一篇下一篇

猜你喜欢

热点阅读