js 异步转同步

在项目中有些逻辑或者请求依赖另外一个异步请求,你们经常使用的方法是回调函数。如今有个高大上的解决方案:await async 。ios

async 是“异步”的简写,而 await 能够认为是 async wait 的简写。因此应该很好理解 async 用于申明一个 function 是异步的,而 await 用于等待一个异步方法执行完成。而且await 只能出如今 async 函数中,不然会报错。axios

async做用:异步

当调用一个 async 函数时,会返回一个 Promise 对象。当这个 async 函数返回一个值时,Promise 的 resolve 方法会负责传递这个值;当 async 函数抛出异常时,Promise 的 reject 方法也会传递这个异常值。async

async 函数中可能会有 await 表达式,这会使 async 函数暂停执行,等待 Promise  的结果出来,而后恢复async函数的执行并返回解析值(resolved)。函数

await做用:url

await 表达式会暂停当前 async function 的执行,等待 Promise 处理完成。若 Promise 正常处理(fulfilled),其回调的resolve函数参数做为 await 表达式的值,继续执行 async functionspa

若 Promise 处理异常(rejected),await 表达式会把 Promise 的异常缘由抛出。另外,若是 await 操做符后的表达式的值不是一个 Promise,则返回该值自己。code

来个栗子:对象

function resolveAfter2Seconds() { return new Promise(resolve => { setTimeout(() => { resolve('resolved'); }, 2000); }); } async function asyncCall() { console.log('calling1'); var result = await resolveAfter2Seconds(); console.log(result); console.log('calling2'); // expected output: 'calling1','resolved','calling2'
 } asyncCall();

结合实际:blog

   function getData() { return  axios.get('/url') } async function asyncCall() { var {data} = await getData(); console.log(data) } asyncCall();

须要注意的:

function getData1() { console.log(new Date()) return new Promise(resolve => { setTimeout(() => { resolve('resolved'); }, 2000); }); } function getData2() { console.log(new Date()) return new Promise(resolve => { setTimeout(() => { resolve('resolved2'); }, 2000); }); } async function asyncCall() { var data1 = await getData1(); var data2 = await getData2();
 console.log(data1) console.log(data2) } asyncCall();

结果:

Mon Apr 29 2019 14:42:14 GMT+0800 (中国标准时间)
 Mon Apr 29 2019 14:42:16 GMT+0800 (中国标准时间)
 resolved
 resolved2

能够看出 getData2 在 getData1执行完后才执行,若是getData2不依赖getData1的返回值,会形成时间的浪费。能够改为下面这样:

function getData1() { console.log(new Date()) return new Promise(resolve => { setTimeout(() => { resolve('resolved'); }, 2000); }); } function getData2() { console.log(new Date()) return new Promise(resolve => { setTimeout(() => { resolve('resolved2'); }, 2000); }); } async function asyncCall() { var data1 = getData1(); var data2 = getData2(); data1 = await data1 data2 = await data2 console.log(data1) console.log(data2) } asyncCall();

结果:

Mon Apr 29 2019 14:51:52 GMT+0800 (中国标准时间)
Mon Apr 29 2019 14:51:52 GMT+0800 (中国标准时间)

resolvedresolved2

相关文章
相关标签/搜索