-
-
Save jagged3dge/1ae038cf050662986121 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var db = require('../models') | |
var Promise = require('bluebird') | |
req.User.getPosts({ | |
include: [ | |
{ model: db.User, attributes: ['displayName', 'name', 'profilePicture'] }, | |
{ model: db.Game, attributes: ['name'] } | |
] | |
}) | |
.then(function(posts) { | |
var promises = [] | |
var post | |
posts.forEach(function(p) { // JS Closure | |
promises.push( | |
Promise.all([ // Declare and resolve 2nd array of promises for each extra data attribute being fetched from DB, then .spread() it for each result | |
db.PostLikes.count({ where: { PostId: p.id } }), | |
db.Comment.count({ where: { PostId: p.id } }) | |
]) | |
.spread(function(likes, comments) { // Maps results from the 2nd promise array | |
post = p.toJSON() | |
post.likes = likes | |
post.comments = comments | |
return post | |
}) | |
) | |
}) | |
return Promise.all(promises) // Resolve 1st promises array | |
}).then(function(posts) { | |
res.send(posts) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This was hugely helpful in understanding promises, thanks for taking the time to post and update!