美文网首页
Promise简单实现

Promise简单实现

作者: 前端_高手 | 来源:发表于2020-09-15 11:43 被阅读0次

通过实现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比较关键的链式调用

相关文章

网友评论

      本文标题:Promise简单实现

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