es6 promise原理是什么?
es6 promise实现可以简单写一写么?55
4条回答 默认 最新
- Alice_czy 2021-07-16 17:03关注
// 三个常量⽤于表示状态
const PENDING = 'pending'
const RESOLVED = 'resolved'
const REJECTED = 'rejected'
function MyPromise(fn) {
const that = this
this.state = PENDING
// value 变量⽤于保存 resolve 或者 reject 中传⼊的值
this.value = null
// ⽤于保存 then 中的回调,因为当执⾏完 Promise 时状态可能还是等待中,这时候应该把
that.resolvedCallbacks = []
that.rejectedCallbacks = []
function resolve(value) {
// ⾸先两个函数都得判断当前状态是否为等待中
if(that.state === PENDING) {
that.state = RESOLVED
that.value = value
// 遍历回调数组并执⾏
that.resolvedCallbacks.map(cb=>cb(that.value))
}
}
function reject(value) {
if(that.state === PENDING) {
that.state = REJECTED
that.value = value
that.rejectedCallbacks.map(cb=>cb(that.value))
}
}
// 完成以上两个函数以后,我们就该实现如何执⾏ Promise 中传⼊的函数了
try {
fn(resolve,reject)
}cach(e){
reject(e)
}
}
// 最后我们来实现较为复杂的 then 函数
MyPromise.prototype.then = function(onFulfilled,onRejected){
const that = this
// 判断两个参数是否为函数类型,因为这两个参数是可选参数
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : v=>v
onRejected = typeof onRejected === 'function' ? onRejected : e=>throw e
// 当状态不是等待态时,就去执⾏相对应的函数。如果状态是等待态的话,就往回调函数中 push
if(this.state === PENDING) {
this.resolvedCallbacks.push(onFulfilled)
this.rejectedCallbacks.push(onRejected)
}
if(this.state === RESOLVED) {
onFulfilled(that.value)
}
if(this.state === REJECTED) {
onRejected(that.value)
}
}本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 vika文档如何与obsidian同步
- ¥15 华为手机相册里面的照片能够替换成自己想要的照片吗?
- ¥15 陆空双模式无人机飞控设置
- ¥15 sentaurus lithography
- ¥100 求抖音ck号 或者提ck教程
- ¥15 关于#linux#的问题:子进程1等待子进程A、B退出后退出(语言-c语言)
- ¥20 web页面如何打开Outlook 365的全球离线通讯簿功能
- ¥15 io.jsonwebtoken.security.Keys
- ¥15 急,ubuntu安装后no caching mode page found等
- ¥15 联想交换机NE2580O/NE1064TO安装SONIC