Use async and await asynchronous operations to solve the problem of fs module asynchronous read/write and synchronization results in node. js, asyncnode. js

Source: Internet
Author: User

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
 

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.