脚本宝典收集整理的这篇文章主要介绍了简单的promise源码,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
1 class Promise {
2 constructor (executor) {
3 // 控制异步执行的状态
4 this.PEnding = "pending"
5 // 用来保存异步执行的结果
6 this.data = undefined
7 // 使用箭头函数 让this指向 当前实例对象
8 const resolve = val => {
9 if (this.pending === 'pending'){
10 this.pending = "fulfilled" //修改状态
11 this.data = val //保存异步执行的结果
12 console.LOG(val)
13 }
14 }
15 const reject = val => {
16 if (this.pending === 'pending') {
17 this.pending = "rejected" //修改状态
18 this.data = val //保存异步执行的结果
19 console.log(val)
20 }
21 }
22
23 executor(resolve, reject) //exector是一个执行器,传入resolve和reject方法,进入会立即执行
24 } 25 }26 27 module.exports = PRomise
首先分析其原理
promise就是一个类 在执行类的时候需要传递一个执行器进去,执行器会立即执行
Promise中有三种状态,分别为成功-fulfilled 失败-rejected 等待-pending pending -> fulfilled pending -> rejected 一旦状态确定就不可更改
resolve 和 reject函数是用来更改状态的 resolve:fulfilled reject:rejected
then方法内部做的事情就是判断状态 如果状态是成功,调用成功回调函数 如果状态是失败,就调用失败回调函数 then方法是被定义在原型对象中的
then成功回调有一个参数,表示成功之后的值;then失败回调有一个参数,表示失败后的原因
以上是脚本宝典为你收集整理的简单的promise源码全部内容,希望文章能够帮你解决简单的promise源码所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。