Promise use and implementation of source code

The use of 01

const Promise = require('./P01.js');

const p = new Promise((resolve, reject) = > {
    / / ajax, timer
    console.log(123);
    // throw new Error('Error');
    resolve('It worked');
    // reject(' reject ');
});


p.then((data) = > {
    console.log(data, 'success01');
}, (err) = > {
    console.log(err, 'fail01');
});

p.then((data) = > {
    console.log(data, 'success02');
}, (err) = > {
    console.log(err, 'fail02');
});

console.log(456);

/* myFunc 123 success01 success02 456 */
Copy the code

Promise source 01

const DENG = 'DENG';    / / wait state
const CHENG = 'CHENG';  / / success
const SHI = 'SHI';      / / failure mode
class Promise {
    constructor(myFunc) {
        console.log('myFunc');
        this.status = DENG;
        // Successful parameters
        this.value = undefined;
        // Failed argument
        this.reason = undefined;
        // Failed callback function
        let reject = (r) = > {
            if (this.status === DENG) {
                this.status = SHI;
                this.reason = r; }};// Success callback function
        let resolve = (v) = > {
            if (this.status === DENG) {
                this.status = CHENG;
                this.value = v; }}// Exception Handling 01
        try {
            myFunc(resolve, reject);
        } catch(error) { reject(error); }}// Then method on the prototype chain
    then(onfulfilled, onrejected) {
        // There are three types of discussion
        / / success
        if (this.status === CHENG) {
            onfulfilled(this.value);
        }
        / / failure mode
        if (this.status === SHI) {
            onrejected(this.reason);
        }
        / / wait state
        if (this.status === DENG) {
            console.log('DENG'); }}}module.exports = Promise;
Copy the code

Use the 02- asynchronous timer

const Promise = require('./P01.js');

const p = new Promise((resolve, reject) = > {
    setTimeout(() = > {
        if (Math.random() > 0.5) {
            resolve('> 0.5');
        } else {
            reject('< = 0.5'); }},1000);
});


p.then((data) = > {
    console.log('success01', data);
}, (err) = > {
    console.log('fail01' + err);
});

p.then((data) = > {
    console.log('success02', data);
}, (err) = > {
    console.log('fail02' + err);
});

Success01 >0.5 Success02 >0.5 */
Copy the code

02- Asynchronous timer

const DENG = 'DENG';    / / wait state
const CHENG = 'CHENG';  / / success
const SHI = 'SHI';      / / failure mode
class Promise {
    constructor(myFunc) {
        console.log('myFunc');
        this.status = DENG;
        // Successful parameters
        this.value = undefined;
        // Failed argument
        this.reason = undefined;
        // Array of asynchronous functions
        this.resolveCallbacks = [];
        this.rejectCallbacks = [];

        // Failed callback function
        let reject = (r) = > {
            if (this.status === DENG) {
                this.status = SHI;
                this.reason = r;
                this.rejectCallbacks.forEach(fn= >fn()); }};// Success callback function
        let resolve = (v) = > {
            if (this.status === DENG) {
                this.status = CHENG;
                this.value = v;
                this.resolveCallbacks.forEach(fn= >fn()); }}// Exception Handling 01
        try {
            myFunc(resolve, reject);
        } catch(error) { reject(error); }}// Then method on the prototype chain
    then(onfulfilled, onrejected) {
        // There are three types of discussion
        / / success
        if (this.status === CHENG) {
            onfulfilled(this.value);
        }
        / / failure mode
        if (this.status === SHI) {
            onrejected(this.reason);
        }
        / / wait state
        if (this.status === DENG) {
            // Save the success callback so that it can be called later when the state is determined
            this.resolveCallbacks.push(() = > {
                onfulfilled(this.value);
            });
            // Save the failure callback so that it can be called later when the state is determined
            this.rejectCallbacks.push(() = > {
                onrejected(this.reason); }); }}}module.exports = Promise;
Copy the code

Use the 03- chain call

const fs = require('fs');

/ / encapsulation Promise
function readFile(name, encoding) {
    return new Promise((resolve, reject) = > {
        fs.readFile(name, encoding, function (err, data) {
            if (err) return reject(err);
            resolve(data);
        });
    });
}
/* ### a Promise instance can call then consecutively, chain-1. The last return from then was an instance of Promise, and if it was in a successful state, it would call back on success. If it was in a failed state, it would call back on failure - 2. The last return then 10 | | [] undefined, next time then success callback - 3. The last THEN throw will return the next THEN failure callback */
readFile('./c1.txt'.'utf-8').then((data) = > {
    console.log('s1', data);
    / / * * * * *
    return readFile('./b.txt'.'utf-8');
    // return 30;
    // throw new Error('err');
    / / return,3,5 [1];
}, (err) = > {
    console.log('r1', err);
    //--------
}).then((data) = > {
    console.log('s2', data);
}, (err) = > {
    console.log('r2', err);
    //--------
}).then((data) = > {
    console.log('s3', data);
}, (err) = > {
    console.log('r3', err);
});


/ / print first
console.log(111);
Copy the code

03- Chain call

Copy the code

await / async