zoukankan      html  css  js  c++  java
  • 实现一个简易的promise

    //promise里面只有三个状态,且三个状态的转换形式有两种
    //由pending转换为fulfilled,由pending转换为rejected
    
    //Promise的构造函数参数是一个函数,函数的参数分别为resolve和reject,两者也均为一个函数
    //then中是实际要执行的函数,将传递进来的值传给resolve和reject对应的参数
    const PENDING = 'PENDING'
    const FULFILLED = 'FULFILLED'
    const REJECTED = 'REJECTED'
    class YPromise {
        constructor(cb) {
            this.state = PENDING;
            this.value = null;
            //承诺完成的回调列表
            this.fulfilledCbs = [];
            //承诺被拒绝的回调列表
            this.rejectedCbs = [];
    
            let resolve = data => {
                setTimeout(() => {
                    if (this.state !== PENDING) return;
                    //更改状态
                    this.state = FULFILLED;
                    this.value = data;
                    this.fulfilledCbs.forEach(c => {
                        this.value = c(this.value);
                    })
    
                }, 0);
    
            }
            let reject = reason => {
                setTimeout(() => {
                    if (this.state !== PENDING) return;
                    this.state = REJECTED;
                    this.reason = reason;
                    this.rejectedCbs.forEach(c => {
                        this.reason = c(this.reason);
                    })
    
                }, 0);
            }
            cb(resolve, reject);
        };
        then(onFulfilled, onRejected) {
            if (typeof onFulfilled === 'function') {
                this.fulfilledCbs.push(onFulfilled);
            }
            if (typeof onRejected === 'function') {
                this.rejectedCbs.push(onRejected);
            }
            return this;//返回整个构造函数可以继续调用then方法
        }
    }
    
    let promise = new YPromise((resolve, reject) => {
        if (4 > 1) {
            resolve('hi');
        } else {
            reject(4大于1')
        }
    })
    
    fulfilledCbs = [data => data + 'world']
    promise.then(data => {
        return data + ' world';
    }).then(data => {
        return data + '!';
    }).then(data => {
        console.log(data);
    })
  • 相关阅读:
    调整数组顺序使奇数位于偶数前面
    数值的整数次方
    矩形覆盖
    变态跳台阶
    跳台阶
    ubuntu图形界面切换文字界面(文字界面切换图形界面)
    Django环境安装、虚拟机端口映射、pycharm远程配置
    sql注入(一)-----数字型
    mysql基本语法
    渗透测试之------信息收集
  • 原文地址:https://www.cnblogs.com/yinping/p/11249728.html
Copyright © 2011-2022 走看看