1 Star 0 Fork 0

level/手写promise

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
jjpromise.js 2.16 KB
一键复制 编辑 原始数据 按行查看 历史
level 提交于 2020-10-17 16:40 . 未完成
const RESOLVE = 'resolved'
const REJECT = 'rejected'
const PENDING = 'pending'
const handlePromise = (result, newPromise, resolve, reject) => {
if (result === newPromise) {
throw new Error('can not return oneself')
}
if ((typeof result === 'object ' && typeof result !== null) || typeof result === 'function')) {
const then = result.then
if (typeof then === 'function') {
}
} else {
resolve(result)
}
}
class JJPromise {
status = PENDING
result = undefined
reason = undefined
onResolvedArr = []
onRejectedArr = []
constructor(execution) {
const resolve = (result) => {
if (this.status === PENDING) {
this.result = result
this.status = RESOLVE
this.onResolvedArr.map((fn) => fn())
}
}
const reject = (reason) => {
if (this.status === PENDING) {
this.reason = reason
this.status = REJECT
this.onResolvedArr.map((fn) => fn())
}
}
execution(resolve, reject)
}
then(onResolved, onRejected) {
const newPromise = new JJPromise((resolved, reject) => {
if (this.status === RESOLVE) {
setTimeout(() => {
const result = onResolved(this.result)
handlePromise(result, newPromise, resolve, reject)
}, 0);
}
if (this.status === REJECT) {
setTimeout(() => {
const result = onRejected(this.reason)
handlePromise(result, newPromise, resolve, reject)
}, 0);
}
if (this.status === PENDING) {
this.onResolvedArr.push(() => {
onResolved(this.result)
handlePromise(result, newPromise, resolve, reject)
})
this.onRejectedArr.push(() => {
onRejected(this.result)
handlePromise(result, newPromise, resolve, reject)
})
}
})
return newPromise
}
}
module.exports = JJPromise
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/keiferr/promise-by-hand.git
git@gitee.com:keiferr/promise-by-hand.git
keiferr
promise-by-hand
手写promise
master

搜索帮助