什么是Promise
青铜段位
class MyPromise {
constructor(fn) {
this.status = 'penging'
this.fulfilled = null
this.rejected = null
this.finallyFn = null
const onResolvedCallback = (value) => {
this.status = 'fulfilled'
this.fulfilled(value)
this.finallyFn(value)
}
const onRejectedCallback = (value) => {
this.status = 'rejected'
this.rejected(value)
this.finallyFn(value)
}
fn(onResolvedCallback, onRejectedCallback)
}
then(fn) {
this.fulfilled = fn
return this
}
catch (fn) {
this.rejected = fn
return this
} finally(fn) {
this.finallyFn = fn
return this
}
}
function post() {
return new MyPromise((resolve, reject) => {
setTimeout(() => {
Math.random() > 0.5 ? resolve('成功') : reject('失败')
}, 1000);
})
}
post().then(res => {
console.log(res)
}).catch(err => {
console.log(err)
}).finally(res => {
console.log(res)
})
静态方法
Promise.all
Promise.any
Promise.race
Promise.allSettled