<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>MyPromise</title>
</head>
<body>
<script>
function MyPromise(excuter) {
this.promiseState = 'pending'
this.promiseValue = undefined
this.callbacks = []
resolve = result => {
if(this.promiseState !== 'pending') return
this.promiseState = 'resolved'
this.promiseValue = result
this.callbacks.forEach(fn => {
fn.onResolve(this.promiseValue)
})
}
reject = error => {
if(this.promiseState !== 'pending') return
this.promiseState = 'rejected'
this.promiseValue = error
this.callbacks.forEach(fn => {
fn.onReject(this.promiseValue)
})
}
try {
excuter(resolve, reject)
} catch (e) {
reject(e)
}
}
MyPromise.prototype.then = function(onResolve, onReject) {
if(typeof onResolve !== 'function') {
onResolve = value => value
}
if(typeof onReject !== 'function') {
onReject = reason => {
throw reason
}
}
const callback = type => {
try {
const res = type(this.promiseValue)
if(res instanceof MyPromise) {
res.then(r => {
resolve(r)
}, error => {
reject(error)
})
} else {
resolve(res)
}
} catch (e) {
reject(e)
}
}
if(this.promiseState === 'resolved') {
callback(onResolve)
}
if(this.promiseState === 'rejected') {
callback(onReject)
}
if(this.promiseState === 'pending') {
this.callbacks.push({
onResolve: function() {
callback(onResolve)
},
onReject: function() {
callback(onReject)
}
})
}
}
MyPromise.prototype.catch = function(onReject) {
return this.then(null, onReject)
}
function f() {
return new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve(23)
}, 3000)
})
}
f().then(val => {
console.log(val)
return new MyPromise((resolve, reject) => {
setTimeout(() => {
console.log('123', val + 5)
resolve(val + 5)
}, 7000)
})
}).then(val1 => {
console.log(val1)
})
</script>
</body>
</html>
js的Promise总结
最新推荐文章于 2024-10-16 16:26:58 发布