Node.js asynchronous programming asynchronous function async await keyword

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
console.log('before');
setTimeout(
   () => {
    
     console.log('last');
}, 2000);
console.log('after');

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

  • Synchronous API can get the result of API execution from the return value, but asynchronous API is not possible
    // 同步
  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 ();
  • To get the execution result of the asynchronous API, you must use the callback function
function getMsg (callback) {
    
    
    setTimeout(function () {
    
    
        callback ({
    
     msg: 'Hello Node.js' })
    }, 2000);
}
getMsg (function (msg) {
    
     
    console.log(msg);
});

3. The difference between synchronous API and asynchronous API (code execution order)

  • Synchronous APIs are executed sequentially from top to bottom, the previous code will block the execution of the following code
for (var i = 0; i < 100000; i++) {
    
     
    console.log(i);
}
console.log('for循环后面的代码');
  • Asynchronous API will not wait for the completion of API execution before executing the code down
console.log('代码开始执行'); 
setTimeout(() => {
    
     console.log('2秒后执行的代码')}, 2000);
setTimeout(() => {
    
     console.log('"0秒"后执行的代码')}, 0); 
console.log('代码结束执行');
  • Analysis of code execution order
    Insert picture description here

4. Asynchronous API in Node.js

  • 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.
const fs = require('fs');

fs.readFile('./1.txt', 'utf8', (err, result1) => {
    
    
	console.log(result1)
	fs.readFile('./2.txt', 'utf8', (err, result2) => {
    
    
		console.log(result2)
		fs.readFile('./3.txt', 'utf8', (err, result3) => {
    
    
			console.log(result3)
		})
	})
});
  • Promise is given in ES6 to solve the problem of callback hell

5.Promise

  • The purpose of Promise is to solve the problem of callback hell in Node.js asynchronous programming.
  • Continue to look at the need to read files in sequence
const fs = require('fs');

function p1 () {
    
    
	return new Promise ((resolve, reject) => {
    
    
		fs.readFile('./1.txt', 'utf8', (err, result) => {
    
    
			resolve(result)
		})
	});
}

function p2 () {
    
    
	return new Promise ((resolve, reject) => {
    
    
		fs.readFile('./2.txt', 'utf8', (err, result) => {
    
    
			resolve(result)
		})
	});
}

function p3 () {
    
    
	return new Promise ((resolve, reject) => {
    
    
		fs.readFile('./3.txt', 'utf8', (err, result) => {
    
    
			resolve(result)
		})
	});
}

p1().then((r1)=> {
    
    
	console.log(r1);
	return p2();
})
.then((r2)=> {
    
    
	console.log(r2);
	return p3();
})
.then((r3) => {
    
    
	console.log(r3)
})
  • 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 () => {
    
    };
async function fn () {
    
    }
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.
  • Do the same to read p1, p2, p3 files in sequence
const fs = require('fs');
// 改造现有异步函数api 让其返回promise对象 从而支持异步函数语法
const promisify = require('util').promisify;
// 调用promisify方法改造现有异步API 让其返回promise对象
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)
	console.log(r2)
	console.log(r3)
}
run();

Guess you like

Origin blog.csdn.net/dairen_j/article/details/109178526