下面我将介绍一些promise对象的基础知识,希望对大家有所帮助。
一、 promise的作用
1.解决回调地狱。
2.实现异步操作。
二、 promise的三种状态
1.pending:刚刚创建一个promise实例时,表示初始状态。
2.fulfilled:resolve方法调用时,表示操作成功。
3.rejected:reject方法调用时,表示操作失败
注意!!!这三种状态只能pending→fulfilled或pending→rejected不可逆
三、 Then()方法和Catch()方法(可以链式操作)
then()用于绑定处理操作后的处理程序(成功时执行),catch()只接受一个参数,用于处理操作异常后的业务。
四、then方法的res是上一个then方法的返回值。
以上几点综合以下举个例子:
<script>
let pro = new Promise(function (resolve, reject) {
if (true) {
resolve('操作成功')
} else {
reject('操作失败')
}
})
pro.then(requestA).then(requestB).then(requestC).catch(RequestError);
function requestA(res) {
console.log('请求A成功');
return '请求B下一个就是你了'
}
function requestB(res) {
console.log('上一步的结果' + res);
console.log('请求B成功');
return '请求C下一个就是你了'
}
function requestC(res) {
console.log('上一步的结果' + res);
console.log('请求C成功');
}
function RequestError(res) {
console.log('请求失败');
}
</script>
结果如下:
五、 Promise.all()方法
接受一个数组作为参数,数组的元素是promise实例对象,当参数中实例对象的状态都为fulfilled时,Promise.all()才会有返回值。
六、Promise.race()方法
它的参数要求跟Promise.all()方法一样,不同的是,它的参数中的promise实例,只要有一个状态发生变化(pending→fulfilled或pending→rejected)它就会有返回,其他实例中再发生变化,它也不管了。