1. Synchronous API, asynchronous API

// Path stitching
const public = path.join(__dirname, 'public');
// Request address resolution
const urlObj = url.parse(req.url);
// Read the file
fs.readFile('./demo.txt'.'utf8'.(err, result) = > {
    console.log(result);
});
Copy the code

1.1. API Synchronization: The next API can be executed only after the current API is executed

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

1.2. 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

/ / synchronize
function sum (n1, n2) {
    return n1 + n2;
}
const result = sum (10.20);
Copy the code
/ / asynchronous
function getMsg () {
    setTimeout(function () {
        return { msg: 'Hello Node.js'}},2000);
}
const msg = getMsg ();
Copy the code

3. Callback functions

Define your own functions for others to call.

// getData function definition
function getData (callback) {}
// the getData function call
getData (() = > {});
Copy the code

4. Use the callback function to obtain the result of asynchronous API execution

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, with the preceding code blocking the execution of the following code

for (var i = 0; i < 100000; i++) {
    console.log(i);
}
console.log('Code after the 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 in 2 seconds')}, 2000);
setTimeout(() = > { console.log('Code executed after 0 seconds')}, 0);
console.log('End of code execution');
Copy the code

6. Code execution sequence analysis

console.log('Code starts executing');
setTimeout(() = > {
    console.log('Code executed in 2 seconds');
}, 2000);
setTimeout(() = > {
    console.log('Code executed after 0 seconds');
}, 0);
console.log('End of code execution');
Copy the code

7. Asynchronous apis in Node.js

fs.readFile('./demo.txt'.(err, result) = > {});
Copy the code
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: 'Joe'})}else {
            reject('Failed')}},2000);
});
promise.then(result= > console.log(result); // {name: 'zhang3 '})
       .catch(error= > console.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 () {}

9.1. Async keyword

  1. An ordinary function becomes an asynchronous function by adding the async keyword before its definition
  2. Asynchronous functions return a promise object by default
  3. The return keyword replaces the resolve method in promise objects that return wrapped results inside asynchronous functions
  4. Throw a program exception inside an asynchronous function using the throw keyword
  5. Call the asynchronous function and chain the then method to get the result of the asynchronous function execution
  6. Call an asynchronous function and then chain the catch method to get an error message about the execution of the asynchronous function

9.2. Await keyword

  1. The await keyword can only appear in asynchronous functions
  2. Await promise you can only write promise objects after await you can’t write other kinds of apis
  3. The await keyword suspends the asynchronous function until the promise returns a result