async 是"异步"的意思,await是async wait的简写,顾名思义咱们就能够理解为等待异步函数的执行完成ios
async 函数返回的是一个 Promise 对象,若是在函数中直接 return 一个值,async 会把这个直接量经过 Promise.resolve( ) 封装成 Promise 对象。
咱们能够经过如下这段代码来讲明这个结论:axios
上面咱们说到,await 用于等待 async 函数的返回值
await 不单单用于等 Promise 对象,它能够等任意表达式的结果并发
async function test() { return new Promise((resolve, reject) => { setTimeout(() => { resolve("完成") }, 1000); } ) } console.time('testForEach'); var result = await test() console.log(result) console.timeEnd('testForEach');
咱们能够看到控制台在一秒后输出了"完成"异步
那咱们什么状况下会使用呢?async
当后面的请求依赖前面的请求的值时
举个例子:有一个列表页面,页面须要展现全部我预约的场次信息,第一个接口返回了全部场次id的合集,我须要根据这个合集去请求第二个接口,以此来获取场次的具体信息
函数
async getinfor() { let that = this; let list = await this.getlist(); // 获取列表 let roundlist = await this.getroundlist(list); //根据roundid获取列次 }, getlist() { var that = this; return new Promise((resolve, reject) => { axios .get(url) .then(data => { resolve(data.data.data);//调用resolve()函数返回下一个请求须要的列表 }); }); },
再好比说:签到功能,若签到成功则返回座位历史预定状况,若签到失败则只显示签到失败的弹框
post
async getseathistory() { var msign = await this.handlesign(); swith(msign){ case "sucess": this.$vux.toast.text("签到成功"); ... //进行获取后续座位预定历史相关请求 break; case "fail": this.$vux.toast.text("签到失败"); break; } }, handlesign() { return new Promise((resolve, reject) => { Axios.post(url,data).then(res => { if (res.data.code != 200) { resolve("sucess"); } else if (res.data.code == 200) { resolve("fail"); } }); }); }
须要同时获取列表的多方面信息,并且信息须要多个请求才能得到,可是获取的信息没有依赖关系,能够同时请求
这个时候就须要用到 Promise.all([p1, p2, p3])
咱们再来举个例子:仍是获取预定列表,第一个接口返回了roundid(场次id)和orderid(预定id),咱们须要roundid去请求场次信息,根据orderid请求预定信息,若是这个时候咱们还按照顺序请求的话必然会费时
咱们能够来验证一下:
顺序请求:this
async getinfor() { let that = this; console.time("test"); let list = await this.getlist(); // 获取列表 let roundlist = await this.getroundlist(); //根据roundid获取列次 let getseatnum = await this.getseatnum(); // 抢座成功的获取抢座座次 // Promise.all([that.getroundlist(),that.getseatnum()]).then((value)=>{ // console.log(value) // }) console.timeEnd("test"); }
同时请求:url
async getinfor() { let that = this; console.time("test"); let list = await this.getlist(); // 获取列表 // let roundlist = await this.getroundlist(); //根据roundid获取列次 // let getseatnum = await this.getseatnum(); // 抢座成功的获取抢座座次 Promise.all([that.getroundlist(), that.getseatnum()]).then(value => { console.log(value); console.timeEnd("test"); }); },
咱们能够看到同时请求的速度快spa
当咱们须要请求的信息在逻辑上比较复杂时,能够考虑使用async/await固然也有人说为何不用Promise而要用async/await呢?在实践中咱们能够发现:Promise 方案的死穴 —— 参数传递太麻烦了使用async/await既能够很方便的读取返回值,代码也比较清晰易读