let p1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(1000)
}, 4000)
})
let p2 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve(2000)
}, 3000)
})
let p3 = new Promise((resolve, reject) => {
setTimeout(() => {
reject(3000)
}, 2000)
})
Promise.all([p1, p2, p3]).then(res => {
console.log(res)
}).catch(err => {
console.log(err, '--90')
})
Promise.race([p1, p2, p3]).then(res => {
console.log(res)
})
Promise.allSettled([p1, p2, p3]).then(res => {
console.log(res)
})
Promise.any([p1, p2, p3]).then(res => {
console.log(res)
})
// 手写promise
class MyPromise {
// 构造方法
constructor(executor) {
// 初始化值
this.initValue()
// 初始化this指向
this.initBind()
// 执行传进来的函数
executor(this.resolve, this.reject)
}
initBind() {
// 初始化this
this.resolve = this.resolve.bind(this)
this.reject = this.reject.bind(this)
}
initValue() {
// 初始化值
this.PromiseResult = null // 终值
this.PromiseState = 'pending' // 状态
}
resolve(value) {
// 如果执行resolve,状态变为fulfilled
this.PromiseState = 'fulfilled'
// 终值为传进来的值
this.PromiseResult = value
}
reject(reason) {
// 如果执行reject,状态变为rejected
this.PromiseState = 'rejected'
// 终值为传进来的reason
this.PromiseResult = reason
}
}
console