2 Star 4 Fork 1

癸亥王 / 云导航

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
function.js 2.79 KB
一键复制 编辑 原始数据 按行查看 历史
class MyPromise {
constructor(callback) {
// 初始化状态
this.status = 'pending'
// 初始化成功状态的值
this.value = undefined
// 初始化失败状态的值
this.reason = undefined
// 储存成功状态的回调函数
this.onResolvedCallbacks = []
// 储存失败状态的回调函数
this.onRejectedCallbacks = []
// 定义resolve函数
const resolve = value => {
if (this.status == 'pending') {
this.status = 'resolved'
this.value = value
this.onResolvedCallbacks.forEach(cb => cb())
}
}
const reject = reason => {
if (this.status == 'pending') {
this.status = 'rejected'
this.reason = reason
this.onRejectedCallbacks.forEach(cb => cb())
}
}
callback(resolve, reject)
}
then (onResolved, onRejected) {
const newPromise = new MyPromise((resolve, reject) => {
if (this.status === 'resolved') {
try {
const x = onResolved(this.value)
resolve(x)
} catch (error) {
reject(error)
}
}
if (this.status === 'rejected') {
try {
const x = onRejected(this.reason)
resolve(x)
} catch (error) {
reject(error)
}
}
if (this.status === 'pending') {
this.onResolvedCallbacks.push(() => {
try {
const x = onResolved(this.value)
resolve(x)
} catch (error) {
reject(error)
}
})
this.onRejectedCallbacks.push(() => {
try {
const x = onRejected(this.reason)
resolve(x)
} catch (error) {
reject(error)
}
})
}
})
return newPromise
}
catch (onRejected) {
return this.then(null, onRejected)
}
}
// new Promise(function (resolve, reject) { })
const m = new MyPromise((resolve, reject) => {
setTimeout(() => {
console.log(1)
resolve('成功')
}, 1000)
})
m.then(val => {
console.log(2)
return 11
}).then(val => {
console.log(3)
return new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve('成功2')
}, 1000)
})
}).then(val => {
console.log(val)
throw new Error('error')
}).catch(err => {
console.log(err)
})
// console.log(m)
Go
1
https://gitee.com/laoyaowang/cloud-navigation.git
git@gitee.com:laoyaowang/cloud-navigation.git
laoyaowang
cloud-navigation
云导航
master

搜索帮助