首页 > 其他 > 详细

手写 promies

时间:2020-07-02 22:04:26      阅读:58      评论:0      收藏:0      [点我收藏+]

简单的 Promies 封装

function Promiss(fn) {
    this.state = ‘pending‘ //当前状态
    this.value = null // 成功执行时得到的数据
    this.reason = null // 执行失败时的返回值
    this.resolveCallbacks = [] // 存储回调函数的数组
    this.rejectCallbacks = []
    resolve = value => {
        this.state = ‘resolver‘
        this.value = value
        this.resolveCallbacks.map(cb => cb(this.value))
    }
    reject = reason => {
        this.state = ‘rejected‘
        this.value = value
        this.resolveCallbacks.map(cb => cb(this.reason))
    }
    try {
        fn(resolve, reject)
    } catch (error) {
        reject(error)
    }
}
Promiss.prototype.then = function (onFulfilled, onRejected) {
    if (this.state === ‘pending‘) {
        this.resolveCallbacks.push(onFulfilled)
        this.rejectCallbacks.push(onRejected)
    }
}
new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(‘ok‘)
        }, 2000)
    })
    .then(res => {
        console.log(res);
    })

Promise 原理

  • promise 的出现是为了解决回调地狱的问题,关键在于利用了 js 异步操作最后执行的特性,将回调方法的传递单独操作,不必担心异步代码执行过早
  • promise 的时间线如下
  1. 执行构造参数里的同步代码,将异步操作暂时挂起
  2. 将 then 方法传入的回调函数放入到相应的回调队列里
  3. 开始执行异步操作,执行至 resolve / reject 方法
  4. 在 resolve / reject 方法中改变 promise 的状态,执行 then 方法在步骤2里传入的回调函数

技术分享图片

手写 promies

原文:https://www.cnblogs.com/peaky/p/promies.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!