I\'m writing code using generators and Bluebird and I have the following:
var async = Promise.coroutine;
function Client(request){
this.request = request
As it is mentioned in the Bluebird docs for Promise.coroutine, you need to watch out not to yield
in a series.
var county = yield countryService.countryFor(user.ip); var data = yield api.getCommentDataFor(user.id); var notBanned = yield authServer.authenticate(user.id);
This code has 3 yield
expressions, each of them stopping execution until the particular promise is settled. The code will create and execute each of the async tasks consecutively.
To wait for multiple tasks in parallel, you should yield
an array of promises. This will wait until all of them are settled, and then return an array of result values. Using ES6 destructuring assignments leads to concise code for that:
Client.prototype.fetchCommentData = async(function* (user){
var [county, data, notBanned] = yield [
// a single yield only: ^^^^^
countryService.countryFor(user.ip),
api.getCommentDataFor(user.id),
authServer.authenticate(user.id)
];
if (!notBanned)
throw new AuthenticationError(user.id);
return {
country: country,
comments: data,
notBanned: true
};
});