Asynchronous function syntax has been added in ES7. Asynchronous functions are encapsulated based on Promise objects to solve asynchronous programming. It allows us to write asynchronous code in a synchronous form, so that the code no longer has callback functions nested, so that the code Become clear.
1. What is a synchronous API and what is an asynchronous API
Synchronous API: Only after the current API is executed, can the next API be executed
console.log('before');
console.log('after');
Asynchronous API: The execution of the current API will not block the execution of subsequent code
Most of Node.js are asynchronous APIs. For example, if a requirement needs to read several files in turn, if you want to read files in turn, the execution of the code behind the asynchronous API depends on the execution result of the previous asynchronous API. If you still use the callback function method If it is solved, the problem of callback hell will arise.
The above code solves the problem of callback hell, but it can be seen from the above code that it is very cumbersome, so the asynchronous function syntax is added in ES7.
5. Asynchronous function
Asynchronous function is encapsulated on the basis of Promise object to solve asynchronous programming. It allows us to write asynchronous code in a synchronous form, so that the code no longer has nested callback functions, making the code clear.
How to use asynchronous functions
const fn =async()=>{
};asyncfunctionfn(){
}
async keyword
Add the async keyword before the definition of ordinary functions, ordinary functions become asynchronous functions
Asynchronous functions return promise objects by default
Use the return keyword inside the asynchronous function to return the result. The result will be wrapped in the promise object. The return keyword replaces the resolve method.
Use the throw keyword inside an asynchronous function to throw a program exception
Call the asynchronous function and then call the then method in a chain to obtain the execution result of the asynchronous function
Call the asynchronous function and then call the catch method in a chain to get the error information of the asynchronous function execution
await keyword
The await keyword can only appear in asynchronous functions
await promise await can only write promise objects and write other types of APIs.
The await keyword pauses the execution of the asynchronous function until the promise returns.