Skip to content

Instantly share code, notes, and snippets.

@dhei
Last active December 27, 2017 18:29
Show Gist options
  • Save dhei/f23c7b9d20d8c53a3a697baa077b8b4d to your computer and use it in GitHub Desktop.
Save dhei/f23c7b9d20d8c53a3a697baa077b8b4d to your computer and use it in GitHub Desktop.

ES6 Generator try-finally behavior

  1. Generator try-finally prevents termination from return
  2. The return value of the generator function is the value that was queued prior to entering the finally clause.

Example adapted from Exploring ES6: Generators. The following two ways are equivalent.

  • Invoke .return() on generators:
function* genFunc2() {
    try {
        yield 'first yield';
    } finally {
        yield 'Not done, yet!';
    }
}

> const genObj2 = genFunc2();

> genObj2.next()
{ value: 'first yield', done: false }

> genObj2.return('Result')
{ value: 'Not done, yet!', done: false }

> genObj2.next()
{ value: 'Result', done: true }
  • return statement:
function* genFunc2() {
    try {
        yield 'first yield';
        return 'Result';
    } finally {
        yield 'Not done, yet!';
    }
}

> const genObj2 = genFunc2();

> genObj2.next()
Started
{ value: 'first yield', done: false }

> genObj2.next()
{ value: 'Not done, yet!', done: false }

> genObj2.next()
{ value: 'Result', done: true }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment