Use async and await asynchronous operations to solve the problem of fs module asynchronous read/write and synchronization results in node. js, asyncnode. js
Async await solves the asynchronous problem. These two keywords are proposed by es7. Therefore, the node and browser versions are improved in testing.
Async await operations are implemented based on promise
The async await keywords are used together. If they are used separately, an error is returned.
Await can only be followed by promise objects
If you are not familiar with promise asynchronous operations, go to my promise article.
Promise solves multi-layer nesting and callback hell
What is callback hell?
Writing an instance is a disgusting multi-layer unnested
function a(){ function b(){ function c(){ } }}
Such code is not easy to maintain.
Next, let's take a look at the fs module to solve the problem of asynchronous requests and synchronous results.
// Es7let fs = require ('fs'); function read (url) {// new Promise needs to input an executor // The executor needs to input two functions resolve reject return new Promise (resolve, reject) =>{ // asynchronously reads the file fs. readFile (url, 'utf8', function (err, data) {if (err) {reject (err)} else {resolve (data );}})})}; // async await solves the asynchronous problem. It is used based on the promise // async await keywords. // await can only be followed by the promise object async function getData () {try {// Promise. all () Concurrent read let result = await promise.all(+read('name.txt'},read('age.txt ')]); console. log (result);} catch (e) {console. log (e) ;}} getData (); // Promise solves multi-layer nesting and callback hell // solves asynchronous requests and synchronous results