ES6—— promise 和 async、await
1,Promise
- promise ,承诺
- resolve,实现承诺
- reject,拒绝实现承诺
- pending,苦苦等待
- Promise,构造函数,需要new
- Promise本身不是异步函数,而是解决异步流程化的一种手段方案
- Promise 参数,excutor,执行器
- excutor 参数,resolve、reject 函数
- excutor 是同步执行的
- then 是异步调用的
- pending => resolve 或 pending => reject 只能二者取其一,且只能发生一次
- promise 的成功结果会在最近一个then的成功回调中被接受,失败结果和抛出的错误会在最近一个then的失败回调或catch的回调中被接受
- Promise.all()
- 参数接收一个interable 类型的数据,可迭代的对象,例如:Array,Map,Set等
- 用于多个异步任务并发执行,它的结果创建承诺后使用,等待所有任务结果的完成。
- interable的元素如果是promise,全部成功则返回一个成功结果组成的数组,有promise失败,结果就是第一个失败的promise的失败原因
- 如果interable的元素不是promise,则直接resolve这个元素
- interable内部没有元素,返回空数组
- Promise.race()
- 参数接收一个interable 类型的数据,可迭代的对象,例如:Array,Map,Set等
- 多个异步任务并发执行,谁先完成,就返回谁的结果,无论是成功还是失败
- 如果interable为空数组,那它什么多不返回,因为没有完成的promise,会认为所有promise任务都还是pending中
- Promise 内部的语法糖
Promise.resolve('成功啦')
// 等同于
new Promise((resolve,reject)=>{
resolve('成功啦')
})
Promise.reject('失败了')
// 等同于
new Promise((resolve,reject)=>{
reject('失败了')
})
2,async、await
async、await
是ES7
新增的一种异步解决方案,可以理解为promise
的语法糖
与Promise相比较:
- 比
Promise
更优雅、简介- 更接近于同步写法,代码自上向下执行,复合我们的编程习惯
使用方法
async
放在函数前面,它能把 同步方法变为异步方法,返回值为一个promise
async
是利用一个隐式的Promise,返回一个promise
的状态结果await
也是放在函数前面,它会等后面的 异步方法执行完成,然后再执行后面的代码。- 不需要再像
Promise
的.then
方法使用链式调用
await
是一个操作符
- 正常情况下它只能在
async
内部使用- 等待一个Promise对象产出结果 的操作手段
- 功能是暂停
async
函数的执行,等待Promise
处理后的结果,再继续执行async
函数- 假如Promise结果是rejected,失败,会抛出异常
// Promise 的 链式调用 ——————————————————————————
function (){
axios.get('url').then(res=>{
//在链式调用中操作结果
console.log(res)
})
}
//async 和 await 的同步式执行 ————————————————————————————————————
async function (){
//利用await直接将异步的请求结果取出,不再需要链式调用
let res = await axios.get('url')
console.log(res)
}
3,Promise 和 async、await
async、await
并不能替代Promise
,而是两者之间相互配合,更好的处理异步Promise
是作为一个容器,来处理异步操作- 而
async、await
更直观的作用是:处理Promise
异步操作的结果