zoukankan      html  css  js  c++  java
  • 从底层来看Promise

    感悟:有的知识你从”底层“来看会觉得很清晰!

    注意:这个源码并不是实际的Promise实现。我主要是想主要是想通模仿实现Promise来学习!

    class Promise {
        constructor(executor) {
            this.resolvedCallbacks = [];
            this.rejectedCallbacks = [];
            this.state = "PENDING";
            this.value = "";
            //这里解释了为什么必是传入resolve,reject;
            executor(this.resolve.bind(this), this.reject.bind(this));
        }
    
        resolve(value) {
            if (this.state === 'PENDING') {
                // 解释了为什么执行了resolve方法会将promise
                this.state = "RESOLVED";
                // 这里解释了为什么resolve传入的值会改变promise的value属性
                this.value = value;
    
                this.resolvedCallbacks.map(callback => callback(value));
            }
        }
        reject(value) {
            if (this.state === 'PENDING') {
                // 解释了为什么执行了reject方法会将Promise的实例状态变为REJECTED
                this.state = "REJECTED";
                // 这里解释了为什么reject传入的值会改变promise的value属性
                this.value = value;
    
                this.rejectedCallbacks.map(callback => callback(value));
            }
        }
    
    
        then(onFulfilled, onRejected) {
            if (this.state === "PENDING") {
                this.resolvedCallbacks.push(onFulfilled);
                this.rejectedCallbacks.push(onRejected);
            }
    
            if (this.state === "RESOLVED") {
                onFulfilled(this.value);
            }
            if (this.state === 'REJECTED') {
                onRejected(this.value);
            }
        }
    }
    
    慢慢来,比较快!基础要牢,根基要稳!向大佬致敬!
  • 相关阅读:
    Java Native Method
    SQL语句优化
    Ibatis的环境搭建以及遇到的问题解决
    Java 构建器
    SpringMVC自定义视图 Excel视图和PDF视图
    java 枚举的常见使用方法
    mysql 根据某些字段之和排序
    MFC The Screen Flickers When The Image Zoomed
    How To Debug Qmake Pro File
    Gcc And MakeFile Level1
  • 原文地址:https://www.cnblogs.com/rookie123/p/14612671.html
Copyright © 2011-2022 走看看