[javascript] What's the yield keyword in JavaScript?

I am also trying to understand the yield keyword. Based my current understanding, in generator, yield keyword works like a CPU context-switch. When yield statement is run, all states (for example, local variables) are saved.

Besides this, a direct result object will be returned to the caller, like { value: 0, done: false }. The caller can use this result object to decide whether to 'wake up' the generator again by calling next() (calling next() is to iterate the execution).

Another important thing is that it can set a value to a local variable. This value can be passed by the 'next()' caller when 'waking up' the generator. for example, it.next('valueToPass'), like this: "resultValue = yield slowQuery(1);" Just like when waking up a next execution, caller can inject some running result to the execution (injecting it to local variable). Thus, for this execution, there are two kind of state:

  1. the context that saved in the last execution.

  2. The injected values by this execution's trigger.

So, with this feature, the generator can sort out multiple async operations. The result of first async query will be passed to the second one by setting local variable (resultValue in above example). The second async query can only be triggered by the first's async query's response. Then the second async query can check the local variable value to decide next steps because the local variable is an injected value from first query’s response.

The difficulties of async queries are:

  1. callback hell

  2. lose of context unless passing them as parameters in the callback.

yield and generator can help on both.

Without yield and generator, to sort out multiple async query requires nested callback with parameters as context which does not easy to read and maintain.

Below is a chained async queries example which running with nodejs:

const axios = require('axios');

function slowQuery(url) {        
    axios.get(url)
    .then(function (response) {
            it.next(1);
    })
    .catch(function (error) {
            it.next(0);
    })
}

function* myGen(i=0) {
    let queryResult = 0;

    console.log("query1", queryResult);
    queryResult = yield slowQuery('https://google.com');


    if(queryResult == 1) {
        console.log("query2", queryResult);
        //change it to the correct url and run again.
        queryResult = yield slowQuery('https://1111111111google.com');
    }

    if(queryResult == 1) {
        console.log("query3", queryResult);
        queryResult =  yield slowQuery('https://google.com');
    } else {
        console.log("query4", queryResult);
        queryResult = yield slowQuery('https://google.com');
    }
}

console.log("+++++++++++start+++++++++++");
let it = myGen();
let result = it.next();
console.log("+++++++++++end+++++++++++");

Below is the running result:

+++++++++++start+++++++++++

query1 0

+++++++++++end+++++++++++

query2 1

query4 0

Below state pattern can do the similar thing for above example:

const axios = require('axios');

function slowQuery(url) {
    axios.get(url)
        .then(function (response) {
            sm.next(1);
        })
        .catch(function (error) {
            sm.next(0);
        })
}

class StateMachine {
        constructor () {
            this.handler = handlerA;
            this.next = (result = 1) => this.handler(this, result);
        }
}

const handlerA = (sm, result) => {
                                    const queryResult = result; //similar with generator injection
                                    console.log("query1", queryResult);
                                    slowQuery('https://google.com');
                                    sm.handler = handlerB; //similar with yield;
                                };

const handlerB = (sm, result) => {
                                    const queryResult = result; //similar with generator injection
                                    if(queryResult == 1) {
                                        console.log("query2", queryResult);
                                        slowQuery('https://1111111111google.com');
                                    }
                                    sm.handler = handlerC; //similar with yield;
                                };

const handlerC = (sm, result) => {
                                    const queryResult = result; //similar with generator injection;
                                    if (result == 1 ) {
                                        console.log("query3", queryResult);
                                        slowQuery('https://google.com');
                                    } else {
                                        console.log("query4", queryResult);
                                        slowQuery('https://google.com');
                                    }
                                    sm.handler = handlerEnd; //similar with yield;
                                };

const handlerEnd = (sm, result) => {};

console.log("+++++++++++start+++++++++++");
const sm = new StateMachine();
sm.next();
console.log("+++++++++++end+++++++++++");

Following is the running result:

+++++++++++start+++++++++++

query1 0

+++++++++++end+++++++++++

query2 1

query4 0