Using return in ES6 generator function

In addition to the thorough answer by @nils, there is one additional way to capture the return value of a generator function, namely as the value of yield* (necessarily inside another generator function):

  function* arrayGenerator(arr) {
    for (const element of arr) 
      yield element
    return arr.length
  }

  function* elementsFollowedByLength(arr) {
    const len = yield* arrayGenerator(arr);
    yield len;
  }

Note the first generator function which returns a value, after it is done yielding the array elements.

The second generator function, through yield*, causes the first generator function to yield all its values. When the first generator function is done and returns, that return value becomes the value of the yield* expression.


return deliveres a return value for an iterators last iteration (when done equals true).

I've simplified your example a bit, since the async operation doesn't seem to be relevant to the question:

function *gen(){
 const val = yield 4;
 return val * 2;
}

var it = gen();
var val = it.next(); // { value: 4, done: false }
console.log(val.value); // 4
var res = it.next(val.value); // { value: 8, done: true }
console.log(res.value); // 8

Whereas without a return value, on the last iteration you will return a value of undefined:

function *gen2(){
 const val = yield 4;
 yield val * 2;
}

var it2 = gen2();
var val2 = it2.next(); // { value: 4, done: false }
console.log(val2.value); // 4
var res2 = it2.next(val2.value); // { value: 8, done: false }
console.log(res2.value); // 8
it2.next(); // { value: undefined, done: true }

Sidenote: As a rule of thumb, there is always one more next call then there are yield statements, which is why there is one more next call in the second example.

Let's say you're using a generator-runner like co, then the value you get after finishing the generator would be the value you return:

co(function* () {
  var result = yield Promise.resolve(true);
  return result;
}).then(function (value) {
  console.log(value); // value equals result
}, function (err) {
  console.error(err.stack);  // err equals result
});

Important: If you are iterating through an iterator, using a for ... of loop or something like Array.from, the return value is going to be ignored (Since you are doing async operations, this is probably not the case anyway):

function *gen(){
 const val = yield 4;
 return val * 2;
}

for (let value of gen()) {
  console.log(value);
}
// 4

In the end, calling a generator just creates an iterator. Whether the final value that the iterator returns is relevant, depends entirely on how you use it.