async + await 是generator的语法糖,generator已经不直接用啦,因此你须要了解的,就是async + await !
(async + await = generator + co ,co库,不了解的能够去github看看了解下~ 几行源码)git
async 就是个promise, async函数能够直接.then((data)=>{ })github
起步:promise
1. await必须结合async才能使用;异步
2. await后面能够跟任何数据,也能够跟同步方法或异步方法;async
例子1:函数
async function fn(){ console.log(0); await 1; console.log(1); await 2; console.log(2); await 3; console.log(3); return 4 } fn().then((data) => { console.log('data', data) }) // 打印: // 0 // 1 // 2 // 3 // data 4
进阶:code
1. await后面跟着setTimeout等非promise写的异步方法,那么async后面的then函数(若then函数里面是同步的), 则会先于await里面的异步方法执行,且async函数中,await后面非promise写的异步方法,若是是接口这种异步,则返回的时间不定,异步流仍然很差控制,看例子2就会发现,awiat函数不是按照书写顺序执行的。(强调!由于下面用了promise会发现另外一片天地!)接口
例子2:generator
async function fn(){ console.log(0); await setTimeout(() => {console.log(200)}, 200); console.log(1); await setTimeout(() => {console.log(100)}, 100); console.log(2); await setTimeout(() => {console.log(50)}, 50); console.log(3); return 'done' } fn().then((data) => { console.log('data', data) }) // 打印: // 0 // 1 // 2 // 3 // data done // 50 // 100 // 200
例子3: 在await 后面用了promise,会发现,异步流彻底可控了!!!同步
async function fn(){ console.log(0); let a = await new Promise((resolve) => { setTimeout(() => {resolve(200)}, 200) }) console.log(1); console.log('a', a); let b = await new Promise((resolve, reject) => { setTimeout(() => {resolve(a + 1)}, 100) }) console.log(2); console.log('b', b); let c = await new Promise((resolve, reject) => { setTimeout(() => {resolve(b + 1)}, 50) }) console.log(3); console.log('c', c); return c } fn().then((data) => { console.log('data', data) }) // 打印: // 0 // 1 // a 200 // 2 // b 201 // 3 // c 202 // data 202
总结:
async + await 是为了让书写的异步流代码可以像同步代码同样,方便控制而产生的。await只有放在async函数里面才能使用,而且只有await后面跟着promise,才可以真正起到控制异步流步骤的效果。