1. Synchronize API sync

The next API can be executed only after the current API is executed

2. Asynchronous API Async

Execution of the current API does not block execution of subsequent code

3. The synchronous API can get the result of the API execution from the return value, but the asynchronous API cannot

function getMsg(){ setTimeout(function(){ return 'hello node.js'; },2000) } const msg = getMsg(); console.log(msg); // undefined // setTimeout will not block the following code (console.log(MSG)),Copy the code

4. callback callback function

function getMsg(callback){
	setTimeout(function(){

		callback({
			msg:'hello  node.js'
		} )
	},2000)
}

getMsg(function(data){
	console.log(data);
});
Copy the code

5. Code execution sequence

Although there is a 0 second timer, it is also an asynchronous API and will be put into the asynchronous code execution area and wait for the synchronous code execution area to complete.

6, callbackhell, callbackhell

When there are multiple asynchronous tasks and we want to do them in some order, we can write another asynchronous API inside the callback function of one asynchronous API, which becomes an unmaintainable callback hell when nested too much

Promise: Fix callback hell in Node.js asynchronous programming

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

1. Asynchronous functions

Asynchronous functions are the ultimate solution to asynchronous programming syntax, allowing us to write asynchronous code in synchronous form without nested callback functions.

  • Async A common function becomes an asynchronous function by adding the async keyword before the definition

  • Asynchronous functions return a promise object by default

  • An asynchronous function returns a result wrapped in a Promise object with the return keyword instead of the resolve method

  • Throw an exception inside an asynchronous function. The code after the throw does not continue

  • Call the asynchronous function and chain call the then method to get the execution result of the asynchronous function

  • Call the catch method to get the error message

  • The await keyword can only appear in asynchronous functions

  • We can only write promis objects after await

  • Awiat can suspend the asynchronous function’s downward execution until a promise returns a result

    const fs = require(‘fs’);

    Const promisify = require(‘util’).promisify; // async API can be modified to return promise object const promisify = require(‘util’).promisify; const readFile = promisify(fs.readFile);

    async function run(){ let r1 = await readFile(‘./1.txt’,’utf8′); let r2 = await readFile(‘./2.txt’,’utf8′); let r3 = await readFile(‘./3.txt’,’utf8′); console.log(r1, r2, r3 ); }

    run();