Promise asynchronous programming solutions

Why use a promise?

  1. Resolve callback hell
    Here Insert Picture Description

    
    fs.readFile(__dirname + '/data/a.txt', (err, data)=>{
        if(!err){
            console.log(data.toString());
            fs.readFile(__dirname + '/data/b.txt', (err, data)=>{
                if(!err){
                    console.log(data.toString());
                }
                fs.readFile(__dirname + '/data/cc.txt', (err, data)=>{
                    if(!err){
                        console.log(data.toString());
                    }
                });
            });
        }
    });
    
    
  2. Asynchronous request Solutions

concept

What is Promise?

  1. promise, promise. In the code, we can understand: I am here to promise commitment, over a certain period of time I give you a result.
  2. Reflected out in Ecmascript 6 is a container object, to encapsulate a general asynchronous operation

So, what to do in this period of time?

  1. We can operate asynchronously;
    such as requesting a data network, time-consuming operation, read and write local files, etc.

Promise of three states

Asynchronous operation is an unpredictable thing, either succeed or fail
internal container there are three states

  1. Pending: Promise object instance is created when the initial state
  2. Fulfilled: state success
  3. Rejected: failed state

NOTE: The state can not be undone

Practice to read the file

Promise to create objects (once created and executed immediately)

  1. Minutiae 1
    when the asynchronous operation is the result of the failure of the object inside the Promise, Promise object container to tell the asynchronous task failed, in fact, the Pending state inside the Promise changed to Rejected
  2. 2 minutiae
    inside Promise target asynchronous operation error does not occur, proved successful, then the Pending state where the inside of the Promise to Resolved
  3. Minutiae 3 (error processing)
    when using Promise do asynchronous process control, about the exception handling can be provided a catch after the last then
    then specify a failure processing function, which can capture all previous Promise object itself, and then internal task error
    current face any exception occurs directly into the catch, including all subsequent Promise then no longer perform

resolve and reject two parameters

resolve the failure to return a result
reject to return successful results
Note: only resolve reject and pass a value, or an array of a plurality of transmission values to use objects.

new Promise((resolve, reject)=>{
    resolve(1, 2, 222, 333);
}).then((data1,data2)=>{
    console.log(data1,data2);
});

operation result:
Here Insert Picture Description

Three asynchronous file reading

const fs = require('fs');

new Promise((resolve, reject)=>{
    fs.readFile(__dirname + '/data/a.txt', (err, data)=>{
        if(err){
            reject(err);
        }
        resolve(data);
    });
}).then((data)=>{
    console.log(data.toString());
    return new Promise((resolve, reject)=>{
        fs.readFile(__dirname + '/data/b.txt', (err, data)=>{
            if(err){
                reject(err);
            }
            resolve(data);
        });
    });
}).then((data)=>{
    console.log(data.toString());
    return new Promise((resolve, reject)=>{
        fs.readFile(__dirname + '/data/cc.txt', (err, data)=>{
            if(err){
                reject(err);
            }
            resolve(data);
        });
    });
}).then((data)=>{
    console.log(data.toString());
});

Three files read-optimized asynchronous

const fs = require('fs');

readFile(__dirname + '/data/b.txt').then((data)=>{
    console.log(data.toString());
    return readFile(__dirname + '/data/a.txt');
}).then((data)=>{
    console.log(data.toString());
    return readFile(__dirname + '/data/cc.txt');
}).then((data)=>{
    console.log(data.toString());
});


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

Exception trap

Finally, add a catch in the chain, if there is a wrong place, the catch will be executed

const fs = require('fs');

readFile(__dirname + '/data/b.txt').then((data)=>{
    console.log(data.toString());
    return readFile(__dirname + '/data/aa.txt');
}).then((data)=>{
    console.log(data.toString());
    return readFile(__dirname + '/data/cc.txt');
}).then((data)=>{
    console.log(data.toString());
}).catch(err => {
    console.log(err);
});


function readFile(...args){
    return new Promise((resolve, reject)=>{
        fs.readFile(...args, (err, data)=>{
            if(err){
                reject(err);
            }
            resolve(data);
        })
    });
}
Published 284 original articles · won praise 126 · views 10000 +

Guess you like

Origin blog.csdn.net/KaiSarH/article/details/104746604