Getting promise value through yield & co

I am trying to figure out how to get the promise value through yield , possibly using "co":

 function *(){ var someVar = yield functionThatReturnsAPromise(); } 

The called function is not a generator, but a normal function. With the above, someVar == Promise , but I want a resolved value. Is there a co or some other library?

+6
source share
2 answers

Yes, co can do it. You will have to wrap the parent function inside a call to co :

 co(function *(){ var someVar = yield functionThatReturnsAPromise(); })() 

someVar inside will be the allowed value. If the promise is rejected, the error can be recorded using the basic try {} catch (e) {} .

+7
source

Typically, the yield action returns the same value in its own paused execution (left side of the exit function) relative to the calling function of the generator. In this simple example, counting from 1 to 5, the input of the output signal is the output of the output to the generator function, as well as to the generator execution path:

 function* inc() { var g = 0; while (true) { g = yield g + 1; } } var incGen = inc(); for (i = incGen.next().value; i <= 5; i = incGen.next(i).value) { console.log(i); // ^ input of generator is last output } 

However, the calling function can also call the generator, but replace the output with the last output with a different value, or even raise an exception to execute the generator. In the case of a promise, a function that returns a promise can produce the result of that promise instead of the promise itself. So in this case:

 var someVar = yield functionThatReturnsAPromise(); ^ output != ^ input 

you want the output to work as a function that takes on the promise as input and returns the allowed promise as the output of the generator function.

So co can do just that for you. All you have to do is pass the generator function to the co function:

 co(function *(){ var someVar = yield functionThatReturnsAPromise(); }) 

To better understand how this works, here is an example of a function that does the same thing as co:

 function async(makeGenerator){ return function (){ var generator = makeGenerator.apply(this, arguments) function handle(result){ if (result.done) return result.value return result.value.then(function (res){ return handle(generator.next(res)) // <- sets output of yield to the promise result }, function (err){ // and returns input promise return handle(generator.throw(err)) // <- throw promise exception to generator function }) } return handle(generator.next()) // <- first time call, input of yield is a promise } } 

source from Forbes Lindesay now famous presentation on this concept

+7
source

All Articles