代码拉取完成,页面将自动刷新
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)
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。