• 简易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');
    })
    
    
  • 相关阅读:
    CHIL-SQL-NULL 函数
    CHIL-SQL-Date 函数
    CHIL-SQL- ALTER TABLE 语句
    CHIL-SQL-AUTO INCREMENT 字段
    CHIL-SQL-VIEW(视图)
    CHIL-SQL-撤销索引、表以及数据库
    CHIL-SQL-CHECK 约束
    CHIL-SQL-DEFAULT 约束
    CHIL-SQL-CREATE INDEX 语句
    CHIL-SQL-FOREIGN KEY 约束
  • 原文地址:https://www.cnblogs.com/king2016/p/6593764.html
Copyright © 2020-2023  润新知