node-Use promise, generator, async/await to read files

tags: nodejs

In node, the module for reading files is fs, which is divided into synchronous reading and asynchronous reading.

const fs = require('fs');

// Read files synchronously
let buf = fs.readFileSync('a.text');

//  Read files asynchronously
fs.readFile('a.text', (err, data) => {
    if (err) {
        console.log('Failed to read file');
    } else {
        console.log(data);
    }
});

In the development process of JavaScript, it has experienced callback functions, Promise objects, Generator functions, and async functions to handle asynchrony. Let's take a look at how the async function handles asynchronous more gracefully. Suppose we need to read three files a, b, and c respectively, the specific code is as follows:

Promise encapsulation of fs module

const readFile = function (src) {
    return new Promise((resolve, reject) => {
        fs.readFile(src, (err, data) => {
            if (err) reject(err);
            resolve(data);
        });
    });
};

Promise writing

readFile('a.text').then(data => {
    console.log(data.toString());
    return readFile('b.text');
}).then(data => {
    console.log(data.toString());
    return readFile('c.text');
}).then(data => {
    console.log(data.toString());
});

Generator's writing

function * ascReadFile () {
    yield readFile('a.text');
    yield readFile('b.text');
    yield readFile('c.text');
}

let g = ascReadFile();
g.next().value.then(data => {
    console.log(data.toString());
    return g.next().value;    
}).then(data => {
    console.log(data.toString());
    return g.next().value;   
}).then(data => {
    console.log(data.toString());
});

async function writing

async function asyncReadFile(){
    let a = await readFile('a.text');
    console.log(a.toString());

    let b = await readFile('b.text');
    console.log(b.toString());

    let c = await readFile('c.text');
    console.log(c.toString());
}

asyncReadFile();

Intelligent Recommendation

Promise, async, await use

1.Promise The understanding of Promise is an object, just an object that can be executed asynchronously. Promise objects have the following three states 1. resolve 2.reject 3.unresolve: Initialization...

async, await, promise to use

When you request must be sequential, but can not send a synchronization request, async, await and promise to help you solve this problem When a request must be sent in order to request multi-layer nes...

Use of async await and promise

async is short for "asynchronous", and await can be considered as short for async wait. So async should be well understood Used to declare that a function is asynchronous, and await is used ...

The use of Promise with async await

The use of Promise with async await Take the WeChat applet as an example: Define a function to send an ajax request: Call from outside: to sum up: Wait for the result of the request through await, and...

Use of Promise, Async and Await

After AWAIT, take a function of Return New Promise and execute it AWAIT can only be placed in the async function Get success results with Async and AWAIT Await Yao () is executed first, wait until thr...

More Recommendation

Use of Async and AWAIT (with Promise)

Async and await Used as follows: Must use Promise to use In the method all, it is synchronized. In the outside of the ALL is asynchronous, the output is output directly, and it will not go to the ALL ...

Use of Async, Await, Promise

Async + AWAIT is equivalent to a syntax of Promise Then, mainly to solve the callback nested in tellen. Async is just used to modify the function, you can use AWAIT after the modification function, an...

Use of Async and AWAIT with Promise

Use of Async and AWAIT with Promise async The function of the keyword declaration is automatically changed to the promise object.returnThe result is the result of promise.Resolve ()! await Keyword mus...

Promise, async, generator use

1. Promise usage 1.1 Simple to use 2. Generator use Simple example Through this example, we can know that the yield processing method of generator will directly return undefined data. 3. Use generator...

Thoroughly understand Promise, Generator, and Async/await

We know that JavaScript is a single-threaded language, and if you don't have asynchronous programming, you have to get stuck. Previously, the asynchronous programming method had the following four Cal...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top