js基础知识—— promise
一、promise
- promise 作用:
- promise 的三个状态
- 持续:pending
- 成功:fulfilled
- 失败:rejected
- promise 只会在持续状态转为成功,或者从持续状态转为失败
- promise的基本语法:promise是js内置的一个构造函数,
- const p = new Promise
- new Promise 得到的对象称为promise对象
- promise上有一些方法:
- then方法,会在promise状态成功的时候执行
- catch方法,会在promise状态失败的时候执行
const p = new Promise(function (resolve,reject){
const timer = Math.ceil(Math.random() * 3000)
console.log('班长买水')
setTimeout(() => {
if (timer > 500){
console.log('买水失败,用时',timer)
reject()
}else {
console.log('买水成功,用时',timer)
resolve()
}
},timer)
p.then(() => {
console.log('promise状态为成功')
})
p.catch(() => {
console.log('promise状态为失败')
})
})
二、promise的链式调用
function fn() {
const p = new Promise(function (resolve, reject) {
const timer = Math.ceil(Math.random() * 3000)
console.log('班长, 去帮我买瓶水')
setTimeout(() => {
if (timer > 1500) {
console.log('买水失败, 用时: ', timer)
reject('买水失败是因为时间超过 1500 毫秒')
} else {
console.log('买水成功, 用时: ', timer)
resolve('买水成功是因为 时间小于 1500 毫秒')
}
}, timer)
})
return p
}
const res = fn()
res.then((str) => {
console.log('如果我这行内容打印, 说明 promise 的状态为 成功', str)
}).catch((str) => {
console.log('如果我这行内容打印, 说明 promise 的状态为 失败', str)
})
function fn() {
const p = new Promise(function (resolve, reject) {
const timer = Math.ceil(Math.random() * 3000)
console.log('班长, 去帮我买瓶水')
setTimeout(() => {
if (timer > 1500) {
reject('超时, 所以买水失败')
} else {
resolve('没有超时, 买水成功')
}
}, timer)
})
return p
}
const res = fn()
res.then((str) => {
console.log(`因为 ${str}, 所以奖励班长 10 个 bug`)
return fn()
}).then((str) => {
console.log('如果我输出了, 表示班长 第二次买水成功')
return fn()
}).then((str) => {
console.log('如果我输出了, 表示班长 第三次买水成功')
}).catch((str) => {
console.log(`如果我输出了, 说明之前某一次买水失败了`)
})
三、promise上的其他方法
function fn() {
const p = new Promise(function (resolve, reject) {
const timer = Math.ceil(Math.random() * 3000)
console.log('班长, 去帮我买瓶水')
setTimeout(() => {
if (timer > 1500) {
reject('超时, 所以买水失败')
} else {
resolve('没有超时, 买水成功')
}
}, timer)
})
return p
}
const res = fn()
res.then(() => {
console.log('成功时执行')
}).catch(() => {
console.log('失败时执行')
}).finally(() => {
console.log('每一次都会执行 (不会考虑成功还是失败)')
})
Promise.all([fn(),fn(),fn()]).then(() => {
console.log('所有参数全部返回成功状态时,会执行');
}).catch(() => {
console.log('所有参数中,有一个为失败状态,便会执行catch');
})
Promise.race([fn(),fn(),fn()]).then(() => {
console.log('这些参数中,结束最快的哪一个状态 为成功时 执行' );
}).catch(() => {
console.log('这些参数中,结束最快的哪一个状态为失败时执行');
})