1.Promise的使用
Promise的使用
let promise = new Promise((resolve, reject) => {
result('success')
reject('error')
})
<!--promise.then(value => {
-->
<!-- console.log(value) //success-->
<!-- return 100-->
<!--}, error => {
-->
<!-- console.log(error)-->
<!--}).then(value => {
-->
<!-- console.log(value) //100-->
<!--})-->
promise
.then()
.then()
.then(value => {
console.log(value)
})
2.Promise实现原理
- Promise是一个类,接收一个执行器(函数)作为参数,执行器会立即执行
- Promise有三个状态 pending fulfilled rejected,状态一旦确定 不可更改
- resolve函数和reject函数的作用:改变状态
- then方法中判断promise的状态,如果是成功 调用resolve,如果是失败 调用reject
- then方法中的回调函数是有参数的,成功回调的参数是异步任务执行成功后的值,失败回调的参数是失败的原因
- promise的then方法可以被多次调用
- then方法可以链式调用,即then方法需要返回一个promise对象
- 下一个then方法回调函数的参数,是上一个then中回调函数的返回值
- 如果上一个then中返回的是一个普通值,直接调用resolve,并且把这个返回值作为resolve的参数;
如果返回的是一个promise对象,判断他的状态来决定调用resolve还是reject(第4步) - then方法中回调函数的返回值不能是当前then返回的promise对象,即promise的循环调用是不被允许的
- promise需要能捕获执行过程中发生的错误,包括promise执行器中的错误,和then方法中发生的错误
- then方法的参数是可选的,如果then没有参数,promise状态会一直向下传递,直到传递给有参数的then方法
- Promise.all()用来解决异步并发问题,他允许我们按照异步操作调用的顺序,得到异步操作执行的结果
- Promise.resolve()用来将给定的值转换成promise对象并返回,这个值可以是普通值,也可以是promise对象
- finally方法,参数是一个回调函数,不管当前promise成功还是失败,finally中的函数都会执行一次,并返回一个promise,可以调用then方法 拿到当前promise执行的结果
- catch方法,参数是当前promise的失败回调,成功回调默认为undefined
Promise实现
const PENDING = 'pending'
const FULFILLED = 'fulfilled'
const REJECTED = 'rejected'
class