ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

深入了解promise,手写实现promise

2021-08-16 01:02:30  阅读:210  来源: 互联网

标签:resolve PromiseResult PromiseState 深入 Promise reject promise 手写 data


什么是Promise

promise是一个构造函数,是用来封装一个异步操作并可以获取其成功/失败的结果值

Promise 对象用于表示一个异步操作的最终完成 (或失败)及其结果值、

 

有哪些异步编程?

1.fs(node)文件操作

2.数据库操作

3.定时器等回调函数

4.发送AJAX请求

........

 

使用Promise的优点

1.支持链式调用,解决回调地狱的问题

2.指定回调函数的方式更加灵活

Promise的执行过程

 

 

 手写实现Promise(一步步搭建Promise)

    let p = new Promise((resolve,reject) => {
        reject('error')
    })
    console.log(p)

此时通过自己手写构造函数覆盖原有的Promise

分析:原生的Promise接受的是一个函数

(此时会报错:reject is not a function)

function Promise(executor){
    executor()
}

对于构造函数中的resolve,reject进行完善

function Promise(executor){
    // 对于初始状态进行赋值
    this.PromiseState = 'pending'
    this.PromiseResult = null
    //绑定this指向
    let _this = this
    function resolve(data){
        // 调用resolve时做的两件事,改变promise的状态(PromiseState),改变结果(PromiseResult)
        _this.PromiseState = 'fulfilled'
        _this.PromiseResult = data
    }
    function reject(data){
        _this.PromiseState = 'rejected'
        _this.PromiseResult = data
    }
    executor(resolve,reject)
}

对于抛出异常的情况处理

    try {
        executor(resolve,reject)
    }catch(e){
        reject(e)
    }

promise状态只能从pending变为fulfilled或rejected,之后不能再变化,对此进行处理

    function resolve(data){
        // 调用resolve时做的两件事,改变promise的状态(PromiseState),改变结果(PromiseResult)
        if(_this.PromiseState !== 'pending') return // reject同理
        _this.PromiseState = 'fulfilled'
        _this.PromiseResult = data
    }

then方法执行回调

    let p = new Promise((resolve,reject) => {
        resolve('success')
    })
    p.then(value => {
        console.log(value)// 此时使用原生的promise,打印出来为‘success'
    },reason => {
        console.log(reason)
    }
    )
Promise.prototype.then = function (onResolved,onRejected){
    if(this.PromiseState === 'fulfilled') {
        onResolved(this.PromiseResult)
    }
    if(this.PromiseState === 'rejected') {
        onRejected(this.PromiseResult)
    }
}

异步任务回调的执行

    let p = new Promise((resolve,reject) => {
        setTimeout(()=>{
            resolve('success')
        },1000)
    })
    p.then(value => {
        console.log(value)//此时不会出现打印结果
    },reason => {
        console.log(reason)
    }
    )
Promise.prototype.then = function (onResolved,onRejected){
    if(this.PromiseState === 'fulfilled') {
        onResolved(this.PromiseResult)
    }
    if(this.PromiseState === 'rejected') {
        onRejected(this.PromiseResult)
    }
    //执行异步任务时,此时PromiseState为pending
    if(this.PromiseState === 'pending') {//增加的部分
        this.callback = {
            onResolved,
            onRejected
        }
    }
}
    function resolve(data){
        // 调用resolve时做的两件事,改变promise的状态(PromiseState),改变结果(PromiseResult)
        if(_this.PromiseState !== 'pending') return // reject同理
        _this.PromiseState = 'fulfilled'
        _this.PromiseResult = data
        //调用成功的回调函数
        if(_this.callback.onResolved) {//增加的部分
            _this.callback.onResolved(data)
        }
    }

执行多个回调的实现

    p.then(value => {
        console.log(value)
    },reason => {
        console.log(reason)
    }
    )
    p.then(value => {//此时只会执行后面的这个then调用
        alert(value)
    },reason => {
        alert(reason)
    }
    )
    if(this.PromiseState === 'pending') {
        this.callback.push({
            onResolved,
            onRejected
        })
    }
    // 对于初始状态进行赋值
    this.PromiseState = 'pending'
    this.PromiseResult = null
    this.callback = []
    //绑定this指向
    let _this = this
    function resolve(data){
        // 调用resolve时做的两件事,改变promise的状态(PromiseState),改变结果(PromiseResult)
        if(_this.PromiseState !== 'pending') return // reject同理
        _this.PromiseState = 'fulfilled'
        _this.PromiseResult = data
        _this.callback.forEach(item => {
            item.onResolved(data)
        })
        //调用成功的回调函数
        if(_this.callback.onResolved) {
            _this.callback.onResolved(data)
        }
    }

同步修改状态then方法返回

标签:resolve,PromiseResult,PromiseState,深入,Promise,reject,promise,手写,data
来源: https://www.cnblogs.com/best-mll/p/15145547.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有