I am attempting to use Bluebird's coroutines as follows:
var p = require('bluebird');
//this should return a promise resolved to value 'v'
var d = p.coroutine(function*(v) { yield p.resolve(v); });
//however this prints 'undefined'
d(1).then(function(v){ console.log(v); });
What is incorrect here?
The strongest feature of Bluebird is that it allows you to “promisify” other Node modules in order to use them asynchronously. Promisify is a concept applied to callback functions. This concept is used to ensure that every callback function which is called returns some value.
Promise. coroutine(GeneratorFunction(... arguments) generatorFunction, Object options) -> function. Returns a function that can use yield to yield promises. Control is returned back to the generator when the yielded promise settles.
A coroutine is a function, marked by the function* syntax, which can suspend itself anywhere in its execution using the yield keyword. It can then be resumed by sending it a value. The sent value will appear as the return value of yield and execution will resume until the next yield .
Quoting the documentation of coroutine
,
Returns a function that can use
yield
to yield promises. Control is returned back to the generator when the yielded promise settles.
So, the function can make use of yield
, but yield
is not used to return value from the function. Whatever you are returning from that function with return
statement will be the actual resolved value of the coroutine function.
Promise.coroutine
simply makes yield
statement wait for the promise to resolve and the actual yield
expression will be evaluated to the resolved value.
In your case, the expression
yield p.resolve(v);
will be evaluated to 1
and since you are returning nothing from the function explicitly, by default, JavaScript returns undefined
. That is why you are getting undefined
as the result.
To fix this, you can actually return the yielded value, like this
var p = require('bluebird');
var d = p.coroutine(function* (v) {
return yield p.resolve(v);
});
d(1).then(console.log);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With