手写简易Promise

promise的用法

new Promise(
  function (resolve, reject) {
    // 一段耗时的异步操作
    resolve('成功') // 数据处理完成
    // reject('失败') // 数据处理出错
  }
).then(
  (res) => {console.log(res)},  // 成功
  (err) => {console.log(err)} // 失败
)

手写promise需要注意的地方
1)接受一个函数(后文称为executor函数)作为参数,executor函数又接收两个参数resolvereject
2)promise三种状态 pending 等待;resolve 成功;reject 失败
3)resolve表示成功的回调,reject表示失败的回调,这是promise的构造方法
4)then方法是promise原型方法。
5)executor函数是立即执行函数,即promise接收参数
6)promise状态不可逆,所以只有在pending状态下才能有异步完成的返回值
7)then方法接收两个函数作为参数,分别代表onfilfilled(成功)和onrejected(失败)

const PENDING = 'pending';
const RESOLVE = 'resolve';
const REJECT = 'reject';
class Promise {
    constructor(executor){
        this.status = PENDING;
        this.value = undefined; //成功返回
        this.reason = undefined; //失败返回
        let resolve = (value) =>{
        //promise对象状态不可逆,所以只有在pending
            if(this.status == PENDING){
                this.status = RESOLVE
                this.value = value
            }
        }
        let reject = (reason) => {
            if(this.status == PENDING){
                this.status = REJECT
                this.reason = reason
            }
        }
        //函数执行发生未知错误直接返回reject
        try{
            executor(resolve,reject) //立即执行函数 即promise接收参数
        }catch(e){
            reject(e)
        }
    }
    //接收两个函数作为参数,分别代表onfilfilled(成功)和onrejected(失败)
    then(onfilfilled,onrejected){
        if(this.status == RESOLVE){
            return onfilfilled(this.value)
        }else{
            return onrejected(this.reason)
        }
    }
}
module.exports = Promise
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。