Zach Smith
Zach Smith

Reputation: 8961

Does JavaScript execute code after a yield statement?

I'm looking at some Github code and it looks like there are expressions after a yield statement.

The link is here, and the code I'm looking at is this:

if (curbyte === LF && lastbyte !== CR || curbyte === CR && curpos < bytesRead - 1) {
    yield _concat(lineBuffer, readChunk.slice(startpos, curpos));

    lineBuffer = undefined;
    startpos = curpos + 1;

    if (curbyte === CR && readChunk[curpos + 1] === LF) {
        startpos++;
        curpos++;
    }
} else if (curbyte === CR && curpos >= bytesRead - 1) {
    lastbyte = curbyte;
}

I would have thought that everything after the line:

yield _concat(lineBuffer, readChunk.slice(startpos, curpos));

and within the same if block would never be reached. Is that incorrect of me?

Upvotes: 1

Views: 681

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230346

Does JavaScript execute code after a yield statement?

Yes, but not right away. When generator yields, it is paused, until iterator calls next() on it. Then the generator resumes the execution, until it yields again.

This is explained here: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Iterators_and_Generators

Upvotes: 2

Related Questions