You spend too much time waiting for input / output from different sources.
In normal promise code, you would use Promise.all to do this, however - people tend to write code that expects requests with generators. Your code does the following:
<-client service-> countryFor.. ''--.. ''--.. ''--.. country server sends response ..--'' ..--'' ..--'' getCommentDataFor ''--.. ''--.. ''--.. ''--.. comment service returns response ..--'' ..--'' ..--'' authenticate ''--.. ''--.. ''--.. authentication service returns ..--'' ..--'' ..--'' Generator done.
Instead, he should do:
<-client service-> countryFor.. commentsFor..''--.. authenticate..''--..''--.. ''--..''--..''--.. country server sends response ''--..--''.. comment service returns response ..--''..--''.. authentication service returns response ..--''..--''.. ..--''..--''..--'' ..--''..--'' ..--'' Generator done
Simply put, all of your I / O must be done in parallel.
To fix this, I would use Promise.props . Promise.props accepts objects and waits until all its properties are resolved (if they are promises).
Remember - generators and promises fit well and match, you just get promises:
Client.prototype.fetchCommentData = async(function* (user){ var country = countryService.countryFor(user.ip); var data = api.getCommentDataFor(user.id); var notBanned = authServer.authenticate(user.id).then(function(val){ if(!val) throw new AuthenticationError(user.id); }); return Promise.props({
This is a very common mistake people make when using generators for the first time.
ascii art is shamelessly taken from Q-Connection by Chris Kowal
Benjamin Gruenbaum Jun 12 '14 at 20:44 2014-06-12 20:44
source share