Search code examples
javascriptgeneratoryield

How to catch a yield in a generator without having unused variable?


I have a warning 'res' is assigned a value but never used no-unused-vars with code similar to this:

function* cancelCredit(action) {
    const res = yield call(/*Nice api call 1*/);
    const res2 =  yield call(/*Nice api call 2*/);
    // Do something with res2
    yield // something
}

How can I hide the first yield of this generator function without having unused variables, without e.g. console.log(res)?


Solution

  • You can ignore any value by using void operator on it:

    void yield call(/*Nice api call 1*/);
    

    (this is particulary usefull for eslint rule that forces all the promises to be explicitly either awaited or voided)

    However, your case is not one of 2.5 cases where you have to void it - you can just ignore the value, it's allowed

    yield call(/*Nice api call 1*/);
    

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield

    Syntax

    yield
    yield expression
    

    Parameters expression Optional The value to yield from the generator function via the iterator protocol. If omitted, undefined is yielded.

    Return value Returns the optional value passed to the generator's next() method to resume its execution.

    Note: This means next() is asymmetric: it always sends a value to the currently suspended yield, but returns the operand of the next yield. The argument passed to the first next() call cannot be retrieved because there's no currently suspended yield.