Async + await is the syntactic sugar of generator, generator is no longer used directly, so all you need to know is async + await! (async + await = generator + co,co library)

Async =>{} then((data)=>{})

Start:

1. Await must be combined with async to be used;

2. Await can be followed by any data and can also be followed by synchronous or asynchronous methods;

Example 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) = > {the console. The log (" data ", data)}) / / print: / / 0 / / 1 / / 2 / / 3/4 / dataCopy the code

Advanced:

1. Await followed by setTimeout and other non-promise asynchronous methods, then the then function following async (if the then function is synchronous) will be executed before the asynchronous method inside await, and async function, Await asynchronous methods that are not written in promise. If an interface is asynchronous, the return time is variable and the asynchronous flow is still difficult to control. As you can see in Example 2, aWIat functions are not executed in written order. (stressed! Because I use the promise below will find another world!

Example 2:

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 the 'done'} fn (). Then ((data) = > {the console. The log (' data 'data)}) / / print:  // 0 // 1 // 2 // 3 // data done // 50 // 100 // 200Copy the code

Example 3: use promise after await and you will find that the asynchronous flow is completely controllable!!

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 202Copy the code

Summary: Async + await is created to make written asynchronous stream code as easy to control as synchronous code. Await can only be used inside an async function, and only await followed by a promise can truly control the steps of an asynchronous flow.