[TOC] #### 1. 前言 ---- async/await 是 ES7 提出的基于 Promise (ES6 中提出的) 的解决异步的最终方案 async + await 的作用: 简化 promise 的异步操作,把 promise 的异步操作编程变为同步的写法 async 将一个函数标记为异步函数,await 需要在异步函数中使用,标记当前操作是异步操作 async + await 必须配合 promise 使用,同时 async 和 await 必须一起使用。即 await 必须在 async 标记的函数中使用 #### 2. 获取成功的结果 --- 在 vue 脚手架和 uniapp 中经常使用的写法 ``` function getProfile() { return new Promise((resolve, reject) => { // 使用定时器模拟接口请求 setTimeout(() => { resolve({ code: 200, msg: "用户信息", data: { id: 1, name: "liang" } }) }, 3000); }); } // 以下代码会执行 输入 123 再执行输出 res function loadData() { getProfile().then(res => { console.log(res); }) console.log(123); } // 下面写法会使 getProfile() 先执行 // 等待三秒后执行完再把得到的结果赋值给左边的res,然后再继续往下执行 async function loadData() { const res = await getProfile() console.log(res); console.log(123); } ``` #### 3. 获取失败的结果 --- 当 Promise 抛出错误信息时,控制台默认是直接抛出异常的 ``` reject('接口请求失败') ```  可以使用 try ... catch 捕获 promise 抛出的错误 ``` try { const res = await getProfile() console.log(res); } catch (error) { console.log('error: ', error); } ``` #### 4. 多个 Promise 的场景 --- 使用 Promise Promise.all 的参数是一个数组,数组的每一项是一个返回的 promise 的函数调用 ```javascript Promise.all([getProfile(), getProfile()]).then(res => { console.log(res, 'res'); }) ``` 使用 await 因为 Promise.all 返回的也是一个 Promise,所以也可以使用 await ```javascript async function loadData() { const res = await Promise.all([getProfile(), getProfile()]) console.log(res); } ``` #### 5. async 标记函数 --- 使用 async 标记一个函数,那么当调用这个函数时,该函数会返回一个 promise 对象 如果没有在 async 函数中 return ,那么 promise 对象的 resolve 就是 undefined 如果在 async 函数中写了 return,那么 promise 对象的 resolve 就是 return 的值 如果 async 里的代码都是同步的,那么这个函数被调用就会同步执行 ``` async function fn(){ console.log('a') } fn() console.log('b') //a //b ``` #### 6. await 等待异步操作执行完成 --- 右侧的表达式的结果就是 await 要等的东西,等到之后,对于 await 来说,分两个情况。是 promise 对象,不是 promise 对象 ``` const res = await getProfile() ``` 如果不是 promise 对象,await 会阻塞后面的代码,先执行 async 外面的同步代码,再回到 async 内部,把这个非 promise 的东西,作为 await 表达式的结果 ``` function fn() { console.log(1) return 'this is return' } async function f1() { const res = await fn() console.log(2) console.log(res); } f1() console.log(3) //1 //3 //2 // this is return ``` 如果 await 等到的是一个 promise 对象,await 也会暂停 async 后面的代码,先执行 async 外面的同步代码,等着 Promise 对象 fulfilled,然后把 resolve 的参数作为 await 表达式的运算结果 ``` function fn() { console.log(1) return new Promise((resolve, reject) => { setTimeout(() => { resolve('this is return') }, 1500); }); } async function f1() { const res = await fn() console.log(2) console.log(res); } f1() console.log(3) //1 //3 //2 // this is return ``` #### 6. async + await 相关文章推荐 --- async 和 await 【简书】: [https://www.jianshu.com/p/b4fd76c61dc9](https://www.jianshu.com/p/b4fd76c61dc9)