1 Synchronous API, asynchronous API

Const public = path.join(__dirname, 'public'); Const urlObj = url.parse(req.url); Fs.readfile ('./demo. TXT ', 'utf8', (err, result) => {console.log(result); });Copy the code

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

console.log('before'); 
console.log('after');
Copy the code

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

console.log('before');
setTimeout(
   () => { console.log('last');
}, 2000);
console.log('after');
Copy the code

2. Difference between synchronous API and asynchronous API (get return value)

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

Function sum (n1, n2) {return n1 + n2; } const result = sum (10, 20); Function getMsg () {setTimeout(function () {return {MSG: 'Hello node.js'}}, 2000); } const msg = getMsg ();Copy the code

3 callback function

Define your own functions for others to call.

Function getData (callback) {} // getData () => {});Copy the code

4 Obtain the result of asynchronous API execution using the callback function

function getMsg (callback) {
    setTimeout(function () {
        callback ({ msg: 'Hello Node.js' })
    }, 2000);
}
getMsg (function (msg) { 
    console.log(msg);
});
Copy the code

5. Difference between Synchronous API and asynchronous API (Code execution order)

① The synchronization API is executed from top to bottom, and the preceding code blocks the execution of the following code

for (var i = 0; i < 100000; i++) { console.log(i); } console.log(' code after for loop ');Copy the code

② Asynchronous apis do not wait for API execution to complete before executing code down

Console. log(' code starts executing '); SetTimeout (() => {console.log(' code executed after 2 seconds ')}, 2000); SetTimeout () = > {the console. The log (' "0 seconds after the execution of code")}, 0). Console. log(' code ends execution ');Copy the code

6 code execution sequence analysis

Console. log(' code starts executing '); SetTimeout (() => {console.log(' code executed after 2 seconds '); }, 2000); SetTimeout (() => {console.log(' code executed after 0 seconds '); }, 0); Console. log(' code ends execution ');Copy the code

7 Asynchronous apis in Node.js

fs.readFile('./demo.txt', (err, result) => {});

var server = http.createServer();
 server.on('request', (req, res) => {});
Copy the code

What if the execution of code following an asynchronous API depends on the execution of the current asynchronous API, but the actual execution of subsequent code does not return the result of the asynchronous API?

fs.readFile('./demo.txt', (err, result) => {}); Console. log(' file read result ');Copy the code

Requirement: Read A file, B file, C file in sequence

8 Promise

Promise came along to solve the problem of callback hell in Node.js asynchronous programming.

let promise = new Promise((resolve, reject) => { setTimeout(() => { if (true) { resolve({name: 'reject ')}else {reject(' reject ')}}, 2000); }); promise.then(result => console.log(result); / / {name: 'Joe'}). The catch (error = > console. The log (error); // failed)Copy the code

9 Asynchronous Functions

Asynchronous functions are the ultimate solution to asynchronous programming syntax. They allow us to write asynchronous code in synchronous form and make code clean without nested callback functions.

const fn = async () => {};

async function fn () {}
Copy the code

(1) the async keyword

1. Add the keyword async before the definition of common functions. Common functions become asynchronous functions

2. Asynchronous functions return a Promise object by default

3. Use the return keyword inside an asynchronous function to return a result that will be wrapped. The return keyword replaces the resolve method in the promise object

Throw a program exception inside an asynchronous function using the throw keyword

5. Call the asynchronous function and then chain call the then method to obtain the execution result of the asynchronous function

6. Call the asynchronous function and then chain call the catch method to get the error message of the asynchronous function execution

(2) the await keyword

1. The await keyword can only appear in asynchronous functions

We can only write promise objects after await. We can’t write other apis

3. Await keyword suspends asynchronous function down until promise returns result