Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bluebird coroutine usage

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?

like image 989
autodidacticon Avatar asked Jun 21 '15 02:06

autodidacticon


People also ask

Why do we use Bluebird promises?

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.

What is promise coroutine?

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.

What is a coroutine Javascript?

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 .


1 Answers

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);
like image 103
thefourtheye Avatar answered Oct 13 '22 14:10

thefourtheye