• 简易promise对象


    promise三种状态: pending(进行中),resolve(成功),reject(失败)

    promise方法then

    function KingPromise(fn) {
        this.status = 'pending';
        this.fn = fn;
        this.result = null;
        this.error = null;
        this.eventQueue = [];
        fn(this.resolve.bind(this), this.reject.bind(this));
    }
    
    
    KingPromise.prototype.resolve = function (res) {
        this.status = 'resolve';
        this.result = res;
        for (var i = 0; i < this.eventQueue.length; i++) {
            this.eventQueue[i](this.result);
        }
    }
    
    KingPromise.prototype.reject = function (err) {
        this.error = err;
        this.status = 'reject';
        for (var i = 0; i < this.eventQueue.length; i++) {
            this.eventQueue[i](this.error);
        }
    }
    
    KingPromise.prototype.then = function (cb) {
        if (typeof cb !== 'function') {
            throw 'then方法参数不是function!';
            return this;
        }
        if (this.status == 'pending') {
            //push到事件队列
            this.eventQueue.push(cb);
        } else if (this.status == 'resolve') {
            cb(this.result);
        } else if (this.status == 'reject') {
            cb(this.error);
        }
        return this;
    }
    

    Demo:

    let doSth = new KingPromise((resolve, reject) => {
        setTimeout(() => {
            console.log('KingPromise_resolve');
            resolve();
        }, 5000)
    });
    
    doSth.then(() => {
        console.log('1');
    })
    doSth.then(() => {
        console.log('2');
    })
    
    
  • 相关阅读:
    [C++]2-5 分数化小数
    [C++]2-4 子序列的和
    [C++]2-3 倒三角形
    [C++]2-2 韩信点兵
    [C++]2-1 水仙花数
    [C++]竞赛模板·数据统计与IO(重定向版与非重定向版)
    数学建模·经验小结
    信息检索·论文写作
    PPT制作
    演讲与语言表达
  • 原文地址:https://www.cnblogs.com/king2016/p/6593764.html
Copyright © 2020-2023  润新知