美文网首页
es6 手写 promise 原理(简单实现)

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

作者: alokka | 来源:发表于2020-05-15 09:51 被阅读0次
    实现:
    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);
    })
    

    相关文章

      网友评论

          本文标题:es6 手写 promise 原理(简单实现)

          本文链接:https://www.haomeiwen.com/subject/xcvqohtx.html