Promise简单实现

通过实现Promise,更好地理解Promise,欢迎有问题的同学评论


class MyPromise {
   callBacks = [];// then的回调push到这个数组中
   state = 'pending';// state初始状态
   value = null;// 保存resolve传递过来的参数
    constructor(fn) {
        fn(this.resolve)
    }
    then = (onFullfilled, onRejected) => {
        if (this.state === 'pending') { // 执行then时候状态还是pending,说明是异步的
            this.callBacks.push(onFullfilled);
            return;
        } else {
            onFullfilled(this.value);
        }
    }
    resolve = (value) => {
        this.state = 'fulfilled'
        this.value = value;
        this.callBacks.forEach(cb => {
            cb(value);
        });
    }
}

// 使用
const promise = new MyPromise((resolve, reject) => {
   resolve('操作成功!');
});
promise.then(res => {
  console.log('成功结果:' + res);
});

下一篇文章我将实现Promise比较关键的链式调用

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。