Promise
分解异步操作,避免回调地狱
//1.promise
//分解异步操作,避免回调地狱
function testMise(value) {
//resolve成功后回调
//reject失败后回调
return new Promise((resolve, reject) => {
//模拟异步请求
setTimeout(() => {
console.log('请求中:', value)
if (value > 0) {
resolve('请求完成');
}
if (value < 0) {
reject('请求失败' + value);
}
}, 2000)
})
}
//promis函数返回.then()成功后执行.catch()失败后执行
testMise(-1).then(res => {
console.log(res)
}).catch(err => {
console.log(err)
})
//2.若有多个异步函数依次执行完成再执行下一个函数时
function testemploy() {
//使用链式调用
//注意then()方法里返回的必须是下一个promise函数
testMise(5).then(res => { //请求中5
return testMise(4) //请求中4
}).then(res => {
return testMise(3) //请求中3
}).then(res => {
//请求失败则进入下一个then第二个参数
return testMise(-1) //请求中-1
}).then(res => {
console.log(res)
}, err => {
console.log(err) //请求失败-1
return testMise(1) //请求中1
}).then(res => {
console.log(res) //请求完成
}).catch(err => {
console.log(err)
})
}
testemploy();
3.Promise.all
全部异步函数执行完成后再执行then回调
//3.Promise.all
// 全部异步函数执行完成后再执行then回调
//res是返回所有函数的参数的数组,
Promise.all([testMise(7), testMise(8), testMise(9), testMise(1)]).then(res => {
console.log('全部执行完成', res)
})
4.Promise.race
有一个执行完成就执行then回调
//4.Promise.race
//有一个执行完成就执行then回调
//res是返回第一个执行完成的参数
Promise.race([testMise(11), testMise(12), testMise(13), testMise(14)]).then(res => {
console.log('有一个执行完成', res)
})
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。