zoukankan      html  css  js  c++  java
  • js 手写 Promise

    /*
     * pending:初始化成功
     * fulfilled:成功
     * rejected:失败
     * */
    function Promise(cback){
        this.status = 'pending';
        this.value = undefined
        this.reason = undefined
        this.fulfilledCallback = undefined;
        this.rejectCallback = undefined;
        
        let resolve = (value)=>{
            if(this.status=='pending'){
                this.status = 'resolve';
                this.value = value;
                this.fulfilledCallback && this.fulfilledCallback();
            }
        };
        let reject = (reason)=>{
            if(this.status =='pending'){
                this.status = 'reject';
                this.reason = reason;
                this.rejectCallback && this.rejectCallback();
            }
        };
        cback(resolve, reject);
    }
    Promise.prototype.then = function(resolve, reject){
        let that = this;
        if (that.status === "resolve") {
            resolve(that.value);
        }
        if (that.status === "reject"){
            reject(that.reason)
        }
        if(that.status == 'pending'){
            that.fulfilledCallback = function(){
                 resolve(that.value)
            }
            that.rejectCallback = function(){
                 reject(that.reason)
            }
        }
    }

    测试

    function test(){
        return new Promise(function(resolve,reject){
                setTimeout(function(){
                    resolve('2秒');
                },2000)
            })
    }
    test()
    .then(function(msg){
        console.log(msg);
    })
  • 相关阅读:
    线程 ,进程和协程
    HTML
    自定义进程池的方法
    线程,进程 ,队列 基本用法总结
    socket 和 SocketServer 模块
    json 和 pickel 详解
    面向对象进阶篇
    面向对象基础 反射
    模块
    字符串格式化
  • 原文地址:https://www.cnblogs.com/bruce-gou/p/10782940.html
Copyright © 2011-2022 走看看