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?
Quoting the documentation of
coroutine,So, the function can make use of
yield, butyieldis not used to return value from the function. Whatever you are returning from that function withreturnstatement will be the actual resolved value of the coroutine function.Promise.coroutinesimply makesyieldstatement wait for the promise to resolve and the actualyieldexpression will be evaluated to the resolved value.In your case, the expression
will be evaluated to
1and since you are returning nothing from the function explicitly, by default, JavaScript returnsundefined. That is why you are gettingundefinedas the result.To fix this, you can actually return the yielded value, like this