The generator function

Fundamentals of Generator functions

function* gen() {
    let a = yield 'a';
    let b = yield 'b';
    return a + b;
}

let it = gen();

let r = it.next();
r = it.next(r.value);
r = it.next(r.value);
console.log(r);
Copy the code

Generator Example of reading a file

const fs = require('fs').promises;

// Method --1. Nice writing more synchronous writing, 2. Can interrupt execution 3
function* read() {
    try {
        let name = yield fs.readFile('./assets/name1.txt'.'utf-8');
        let age = yield fs.readFile('./assets/age.txt'.'utf-8');
        return `${name}---${age}`;
    } catch (e) {
        console.log(e, 'readFunc'); }}Copy the code
// Execute it manually
let it = read();
it.next().value.then(data= > {
    console.log(data);
    it.next(data).value.then(data= > {
        console.log(data);
        let r = it.next(data);
        console.log(r); })});Copy the code
// Automatic execution
function co(it) {
    return new Promise((resolve, reject) = > {
        function next(data) {
            let { done, value } = it.next(data);
            if (done) {
                resolve(value);
            } else {
                Promise.resolve(value).then(
                    (data) = >{ next(data); }, (err) => { it.throw(err); reject(err); }); } } next(); })}Copy the code
// Automatically execute the call method
co(read()).then(data= > console.log(data), err => console.log(err, 'thenFunc'));

Copy the code

Example of async+await reading files

// ES7 syntax async+await - syntax sugar corresponding to generator
// 1. Write async; 2. Return Promise; 3. Interrupt execution
async function read() {
    try {
        let name = await fs.readFile('./assets/name.txt'.'utf-8');
        console.log("Ready to read age.txt");
        let age = await fs.readFile('./assets/age.txt'.'utf-8');
        return `${name}---${age}`
    } catch (e) {
        throwe; }}Copy the code
// Asynchronous function usage - returns promise
read().then(data= > console.log(data, 'succ-then'), err => console.log(err, 'thenErrFunc'));
Copy the code