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);
            }
        }
    }
    
    慢慢来,比较快!基础要牢,根基要稳!向大佬致敬!
  • 相关阅读:
    【windows 10 安装docker for windows】
    【windows本地修改git账号、路径信息】
    【echarts】简单使用流程(java)
    【MySql】explain
    【thymeleaf-标签】th:with
    【MongoDB】Windows:安装与启动
    【thymeleaf-标签】th:if
    Thread类中interrupt()、interrupted()和isInterrupted()方法详解
    java中的锁
    LinkedList集合详解
  • 原文地址:https://www.cnblogs.com/rookie123/p/14612671.html
Copyright © 2011-2022 走看看