js中的 promise

本文包含以下内容:

  • promise是什么
  • promise状态改变
  • promise的使用
  • promise 的其他种写法
  • promise.all
  • promise.race
  • promise的优点
  • 手写一个promise

promise是什么

  • 从语法上来说,promise是一个构造函数
  • 从功能上来说,promise对象用来封装一个异步操作,并可以获取其结果

promise状态改变

  • pending -> resolved
  • pending -> rejected
    一个promise对象只能改变一次状态,无论成功失败都会有一个结果数据;
promise流程图

promise的使用

// 创建promise对象
const p = new Promise((resolve,reject)=>{ //执行器函数 同步回调
    // 执行异步任务
    setTimeout(()=>{
        const time = Date.now()
        if(time %2 == 0){
            resolve('成功啦!!' + time)
        }else{
            reject('失败啦!!' + time)
        }
        
    },1000)
    // 如果成功,调用 resolve(value)
    // 如果失败,调用 reject(reason)   
})  
p.then(
  value=>{
    console.log(value)
  },  
  reason=>{
    console.log(reason)
  }
)

promise 的其他种写法

写一个成功值为 1 的promise对象
写一个失败值为 2 的promise对象

const p1 = new Promise((resolve,reject)=>{
    resolve(1);
})  
const p2 = Promise.resolve(1);
const p3 = Promise.reject(2);

p1.then(value => {console.log(value)})
p2.then(value => {console.log(value)}) 

p3.then(null,reason => {console.log(reason)})
p3.catch(reason => {console.log(reason)})

promise.all

promise.all()函数中传入promise对象数组,数组中只要有一个对象失败了,这个就失败了;
只有所有都成功了,才会成功;

const p1 = new Promise((resolve,reject)=>{
    resolve(1);
})  
const p2 = Promise.resolve(1);
const p3 = Promise.reject(2);

const pAll = Promise.all([p1,p2,p3])
pAll.then(
    value => {
        console.log('成功啦!',value)
    },
    reason =>{
        console.log('失败啦!',reason)
    }
)

promise.race

promise.all()函数中传入promise对象数组,执行的第一个对象(不一定是数组第一个)成功了就成功了,第一个执行对象失败了就失败了;
写法与上面代码一致;


promise的优点

  1. promise 比纯回调函数更加的灵活
  2. promise 支持链式调用,可以解决回调地狱的问题
    回调地狱就是回调函数的嵌套调用;
async / wait: 回调地狱的终极解决方案:

以下代码为伪代码,不能执行

async function request(){
    try{
        const res1 = await dosth1();
        const res2 = await dosth2();
        const res3 = await dosth3();
        console.log('get')
    }catch(error){
        console.log(error);
    }
}

手写一个promise

function Promise(excutor){
    const _this = this
    // 内部属性
    _this.status = 'pending'  //状态值
    _this.data = undefined  //存储结果数据
    _this.callbacks = []  //每个元素的结构
    
    function resolve(value){
        if(_this.status !== 'pending'){
            return
        }
        // 1.改变状态  2.保存value数据  3.立即异步执行回调函数
        _this.status = resolved
        _this.data = value
        if(_this.callbacks.length>0)
        {
            _this.callbacks.forEach(callbackObj =>{
                setTimeout(()=>{
                    callbackObj.onResolved(value)
                })
            })
        }
        
    }
    function reject(reason){
        if(_this.status !== 'pending'){
            return
        }
        // 1.改变状态  2.保存value数据  3.立即异步执行回调函数
        _this.status = rejected
        _this.data = reason
        if(_this.callbacks.length>0)
        {
            _this.callbacks.forEach(callbackObj =>{
                setTimeout(()=>{
                    callbackObj.onRejected(reason)
                })
            })
        }
    }
    
    // 立即同步执行excutor
    try{
        excutor(resolve,reject)
    }catch(error){
        reject(error)
    }   
}

Promise.prototype.then = function(onResolved,onRejected){
    const _this = this

    // 返回一个新的promise对象
    return new Promise((resolve,reject)=>{
        
        onResolved = typeof onResolved==='function'? onResolved:value=>value
        //指定默认的失败回调(实现错误/异常传透的关键点)
        onRejected = typeof onRejected==='function'? onRejected:reason=>{throw reason}
    
        // 调用指定的回调函数,根据执行结果,改变return的promise的状态
        function handle(callback){
            try{
                const res = callback(_this.data)
                if(res instanceof Promise){
                    res.then(resolve,reject)
                }else{
                    resolve(res)
                }
            }catch(error){
                reject(error)
            }           
        }
        
        
        if(_this.status === 'pending'){
            _this.callbacks.push({
                onResolved(){
                    handle(onResolved)
                },
                onRejected(){
                    handle(onRejected)
                }
            })
        }else if(_this.status === 'resolved'){
            setTimeout(()=>{
                handle(onResolved)      
            })
        }else{
            setTimeout(()=>{
                handle(onRejected)
            })
        }
    })
}

Promise.prototype.catch = function(onRejected){
    return this.then(undefined,onRejected)
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 官方中文版原文链接 感谢社区中各位的大力支持,译者再次奉上一点点福利:阿里云产品券,享受所有官网优惠,并抽取幸运大...
    HetfieldJoe阅读 12,755评论 0 29
  • 前言 编程语言很多的新概念都是为了更好的解决老问题而提出来的。这篇博客就是一步步分析异步编程解决方案的问题以及后续...
    李向_c52d阅读 4,688评论 0 2
  • Promise是ES6中所独有的对象,它很抽象,多用于异步js代码中,如:async函数与await一起使用,一个...
    都江堰古巨基阅读 8,609评论 0 0
  • 特点 1.对象的状态不受外界影响。2.一旦状态改变,就不会再变,任何时候都可以得到这个结果。3.无法取消Promi...
    施主画个猿阅读 864评论 0 0
  • Promise是什么   首先通过字面来看,他是一个承诺,意思就是现在我先答应你,以后一定给你兑现;对应到代码中就...
    失心轩阅读 7,534评论 0 2