• 关于promise


    1 先看一段生成 pormise 实例的代码

    1.1 promise 作为一个构造函数 通过 new 创建一个 promise 实力
    1.2 执行器接受两个参数 可接收两个参数 resolve reject

    const promise1 = new Promise((resolve,reject)=>{ // 执行器
    
    })
    
    • 1
    • 2
    • 3

    2 创建 Promise 类 Promise 具有三种状态: pending(进行中) fulfilled(已完成) rejected(已失败)

    const PENDING = 'pending'
    const FULFILLED = 'fulfilled'
    const REJECTED = 'rejected'
    
    • 1
    • 2
    • 3

    2.1 定义一个 MyPromise 类

    class MyPromise1 {
        constructor(name,age){
            // 初始状态为 pending
            this.status = PENDING
    
            this.name = name
            this.age = age
        }
        user(){
            console.log(`我的名字是${this.name},年龄是${this.age}`)
        }
    }
    const myUserPromise = new MyPromise1('憨憨林',18)
    myUserPromise.user()
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    3 resolve 与 reject 作用

    3.1 resolve 函数 将promise 实例状态从 pending 变为 fulilled 在异步操作成功时调用
    3.2 reject 函数 将 promise 实例状态从 pendngg 变为 rejected 在异步操作失败时调用

    const promise2 = new Promise((resolve,reject)=>{
        setTimeout(()=>{
            const rand = Math.random() * 100
            if(rand > 50){
                resolve('成功')
            }else{
                reject('失败')
            }
        },1000)
    })
    promise2.then(res=>{
        console.log(res)
    }).catch(err=>{
        console.log(err)
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    4 MyPromise 类中,我们定义 resolve 函数 和 reject 函数,并在函数体内进行 status、value 或 reason的更新,同时调用 executor 执行器,传入 resolve 和 reject

    class MyPromise2 {
        constructor(executor){
            this.status = 'pending'
            this.value = undefined
            this.reson = undefined
            // 定义 resolve
            const resolve = value => {
                this.status = 'fulfilled'  // 更新状态
                this.value = value  // 更新值
            }
            // 定义 reject
            const reject = reason =>{
                this.status = 'rejected' // 更新状态
                this.reson = reason // 更新值
            }
            // 调用执行器 将 ressolve' 和 'reject' 作为参数传递出去
            executor(resolve,reject)
        }
        
    }
    
    const p1 = new MyPromise2((resolve,reject)=>{
        resolve('success') 
    })
    console.log(p1)
    const p2 = new MyPromise2((resolve,reject)=>{
        reject('error')
    })
    console.log(p2)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    4 执行器 (execotor)函数内改变的几种方式

    // 初始状态
    new Promise((resolve,reject)=>{}) // pending // 初始状态
    
    // 执行resolve 
    new Promise((resolve,reject)=>{ resolve() }) // fulilled // 已成功
    
    // 执行 reject
    new Promise((resolve,reject)=>{reject()}) // rejected // 已失败
    
    // 抛出异常
    new Promise((resolve,reject)=>{ throw new Error('error')}) // rejected // 已失败
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    完整手写promise 流程

    
    /**
     * 手写promise 过程
     * 1 promise 分别有三种状态 1 进行中(pending) 2 完成(fulfilled) 3 失败(reected)
     * */ 
    // 创建一个 类
    class MyPromise {
        constructor(executor){
            // promise 有三种状态 (pending) 进行中 fulfilled(已完成) rejected(已失败)
            this.status = 'pending' // 初始状态
            this.value = undefined // 成功的原因
            this.reason = undefined // 失败的原因
    
            this.onFulfilledCallbacks = [] // 成功回调函数数组
            this.onRejectedCallbacks = [] // 失败回调函数数组
            // 成功
            const resolve = value => {
                if(this.status === 'pending'){
                    this.status = 'fulfilled'
                    this.value = value
                    this.onFulfilledCallbacks.forEach(fn => fn()) // 调用成功的回调函数
                }
            }
            // 失败
            const reject = reason => {
                if(this.status === 'pending'){
                    this.status = 'rejected'
                    this.reason = reason
                    this.onRejectedCallbacks.forEach(fn => fn())
                }
            }
            // 执行器 将成功失败
            try {
                executor(resolve,reject)
            } catch (err){
                executor(err)
            }
        }
        // then 方法
        then(onFulfilled,onRejected){
            return new MyPromise((resolve,reject) => {
                if(this.status == 'fulfilled') {
                    setTimeout(() => {
                        const x = onFulfilled(this.value)
                        x instanceof MyPromise ? x.then(resolve,reject) : resolve(x)
                    })
                }
                if(this.status == 'rejected') {
                    setTimeout(() => {
                        const x = onRejected(this.reason)
                        x instanceof MyPromise ? x.then(resolve,reject) : resolve(x)
                    })
                }
                if(this.status == 'pending') {
                    this.onFulfilledCallbacks.push(() => {
                        setTimeout(() => {
                            const x = onFulfilled(this.value)
                            x instanceof MyPromise ? x.then(resolve,reject) : resolve(x)
                        })
                    })
                    this.onRejectedCallbacks.push(() => {
                        setTimeout(() => {
                            const x = onRejected(this.reason)
                            x instanceof MyPromise ? x.then(resolve,reject) : resolve(x)
                        });
                    })
                }
            })
        }
    }
    
    // 测试
    function p1(){
        return new MyPromise((resolve,reject)=>{
            setTimeout(resolve,1000,'憨憨')
        })
    }
    
    function p2(){
        return new MyPromise((resolve,reject)=>{
            setTimeout(resolve,1000,'林')
        })
    }
    
    p1().then((res)=>{
        console.log(res);
        return p2()
    }).then(ret=>{
        console.log(ret);
    })
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
  • 相关阅读:
    深度学习六十年简史
    戴着人工心脏上脱口秀大会——王十七的充电人生
    第四章 引用计数
    【云原生】微服务架构SpringCloud和Dubbo的区别?
    齐普夫定律在循环神经网络中的语言模型的应用
    ARR过亿,甄云科技姚一鸣:奔向数字采购标准化时代
    MySQL高可用九种方案
    单片机论文参考:1、基于单片机的电子琴
    2023 年和 2024 年人工智能和机器学习会议清单
    瑞吉外卖实战项目全攻略——总结篇
  • 原文地址:https://blog.csdn.net/weixin_49431241/article/details/125853645