zoukankan      html  css  js  c++  java
  • promise 码农

    // executor  function(resolve, reject) { }   );
    const PENDING = 'pending';
    const RESOLVED = 'resolved';
    const REJECTED = 'rejected';

    function MyPromise(executor) {
        status = PENDING;
        data = null;
        callbacks = []; //{onResolve,onReject}

        function resolve(val) {
            debugger;
            this.status = RESOLVED;
            this.data = val;
            if (this.callbacks.length > 0) {
                this.callbacks[0](val);
            }
        }

        function reject(reason) {}

        try {
            executor(resolve, reject);
        } catch (error) {}
        executor(resolve, reject);
    }

    MyPromise.prototype.then = (onResolve, onReject) => {
        this.callbacks.push({
            onResolve,
            onReject
        });
        return new MyPromise((res, rej) => {
            if (this.status === RESOLVED) {
                onResolve(this.data);
            } else if (this.status === RESOLVED) {
                onReject(this.data);
            } else {

            }
        });
    }


    MyPromise.prototype.catch = function (onRejected) {};

    MyPromise.prototype.resolve = function (val) {};

    MyPromise.prototype.reject = function (reason) {};

    var p = new MyPromise(function (res, rej) {
        console.log('init');
        setTimeout(() => {
            debugger;
            res('a');
        }, 1000);
    });
    p.then(
        val1 => {
            console.log(val1);
        },
        reason1 => {

        }
    ).then(
        val2 => {
            console.log(val2);
        },
        reason2 => {

        }
    );

    // 1: init MyPromise,  put a to Quee
    // 2:

    /**
     * output     Micro Quee      Mis Quee
     * init       a
     *
     *
     */

  • 相关阅读:
    C# 5注释
    C# 4关键字
    C# 3练习题
    python之子类调用父类的同名属性和方法
    python之继承
    python之对象删除和输出
    python之r,w,a
    python之类中的方法和属性
    python之面向对象
    python之os对文件的操作
  • 原文地址:https://www.cnblogs.com/dming4/p/13608993.html
Copyright © 2011-2022 走看看