手写一个promise的过程
Posted 小顺石
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了手写一个promise的过程相关的知识,希望对你有一定的参考价值。
const PEDDING = \'PEDDING\';
const RESOLVE = \'RESOLVE\';
const REJECT = \'REJECT\';
// promise 有三种状态
class NewPromise {
// 初始状态为 PEDDING
status = PEDDING
result = undefined;
reason = undefined;
// 发布订阅者模式
// 目的是为了实现异步
onResolveArr = [];
onRejectArr = [];
constructor(exc) {
const resolve = result => {
if (this.status === PEDDING) {
this.result = result
this.status = RESOLVE
// 执行发布者
this.onResolveArr.map(fn => fn())
}
}
const reject = reason => {
if (this.status === PEDDING) {
this.reason = reason
this.status = REJECT
// 执行发布者
this.onRejectArr.map(fn => fn())
}
}
exc(resolve, reject)
}
then(onResolve, onReject) {
if (this.status === RESOLVE) {
setTimeout(() => {
onResolve(this.result)
}, 0)
}
if (this.status === REJECT) {
setTimeout(() => {
onReject(this.reason)
}, 0)
}
// 发布订阅者模式
if (this.status === PEDDING) {
// 将订阅者添加到数组里面
this.onResolveArr.push(() => {
onResolve(this.result)
})
this.onRejectArr.push(() => {
this.onReject(this.reason)
})
}
}
}
// let yan = new Promise((resole, reject) => {
// resole(\'闫大爷真帅\')
// })
// yan.then(res => {
// console.log(res)
// })
let newYan = new NewPromise((resole, reject) => {
setTimeout(()=>{
resole(\'new闫大爷真帅\')
},3000)
})
newYan.then(res => {
console.log(res)
})
console.log(11111111)
以上是关于手写一个promise的过程的主要内容,如果未能解决你的问题,请参考以下文章