Alisa T Morgan
Alisa T Morgan

Reputation: 677

generator function confusion in returned value

I read about generator function, I thought it's more or less the same with async await, but the expected result is different than the actual result.

function* adding() {
  var result = 1 + 1
  return 20 + (yield result)
}

var sum = adding()
console.log(sum.next()) // not returning 22 but 2?
console.log(sum.next(10)) // where is 30 come from?

Upvotes: 0

Views: 36

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370759

The yield keyword pauses the generator function. When you call .next() for the first time, the interpreter goes through the generator until it encounters the first yield. The generator will pause there, and return the expression that follows the yield to the caller of .next(). So, since result starts out at 2, yield result results in the first .next() call returning 2.

When you call .next() with an expression, that expression gets substituted into the generator function where the last paused yield was. So, when .next(10) is called, this line here:

return 20 + (yield result)

turns into

return 20 + (10)

because 10 is what was passed to .next(). So, at the end, 20 + 10 is returned, which is 30.

As you can see, generators are quite different from async/await, though they both deal with controlling asynchronous program flow.

Upvotes: 2

Related Questions