Promise
为避免回调函数出现的回调地域的问题,promise应景而生。
使用
let pro = new Promise((resolve,reject)=>{
//异步操作在此处
})
**参数说明**
resolve 标识执行成功
reject 标识执行失败。
成功后:
pro.then(res=>{
//成功获取到的数据res
})
失败:
pro.catch(err=>{
//失败了!
})
promise状态
三种:
1、pendding:等待
2、fulfilled(resolve):成功
3、reject: 失败
三种状态 只能变化一次。
promise的链式调用
promise通过链式调用解决回调地域的问题
Promise的.then方法返回的还是一个Promise对象,这个Promise的状态是由上一个.then方法中函数的返回值的决定
• 上一个.then返回了一个Promise对象。 这里得到的状态就和这个Promise对象一样
• 上一个.then返回了一个非Promise对象。可以直接在后续函数拿到这个数据
看图
Promise的两个API
1、Promise.all() //全部执行完毕后再进行操作
Promise.all([pro1, pro2]).then(function (result) {
console.log(result);
}).catch(function (err) {
console.log(err);
})
2、 Promise.race() //只要有一个完成就进行操作
Promise.race([pro1, pro2]).then(function (result) {
console.log(result);
}).catch(function (err) {
console.log(err);
})