关于promise

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

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

const promise1 = new Promise((resolve,reject)=>{ // 执行器

})

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

const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'

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()

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)
})

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)

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 // 已失败

完整手写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);
})

你可能感兴趣的:(笔记,javascript,前端,开发语言)