1. The use of asayc asa keyword in front of functions, so that ordinary functions become asynchronous functions

2. Asynchronous async function calls, which are used in the same way as ordinary functions

The async function returns a Promise object

4. Async functions used with await keyword (blocking code down) are asynchronous methods, but blocking

Usage scenarios

Async mainly deals with asynchronous operations,

Requirement: Perform the first step and return the results of the first step to the second step for use. In Ajax, we get the data returned from an interface first, and then use the data returned from the first step to perform the interface call of the second step, so as to achieve asynchronous operation.

Simulate an asynchronous operation of a dice shaker, first through a method after three seconds to get a number of dice, the second step to outputCopy the code
// Basic async functions
let asyncFun = async function(){
    return 1
}
console.log(asyncFun())
// Returns a Promise object


// Usage scenarios
// Shake the dice
function dice(){
    return new Promise((resolve,reject) = >{
        let sino = parseInt(Math.random()*6+1)  // Generate a random decimal between 1 and 6
        setTimeout((a)= >{
            resolve(sino)
        },2000)})}// Asynchronous method
 async function text(){
     let n= await dice()
      //await the variable assignment after the wag method is called after the await keyword
     console.log("Shake it out."+n)  // Finally print out the number rolled out
 }
text()

Copy the code

Conclusion:

1. Async returns a Promise object. When the function executes, it will return an await object and wait until the triggered asynchronous operation is complete before executing the following statement in the function body.

2. Await keyword must be inside async function

3. Need a promise object after await keyword (if not call resolve to convert it)

4. The return result of the await keyword is the result of the Promise execution after ‘7’, which could be resolved or Rejected