Skip to content

Instantly share code, notes, and snippets.

@jagged3dge
Last active March 15, 2023 18:38
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jagged3dge/1ae038cf050662986121 to your computer and use it in GitHub Desktop.
Save jagged3dge/1ae038cf050662986121 to your computer and use it in GitHub Desktop.
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)
})
@mawelsh
Copy link

mawelsh commented Jan 14, 2016

This was hugely helpful in understanding promises, thanks for taking the time to post and update!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment