Created
March 14, 2018 13:51
-
-
Save rivertam/f88a9b5c6937964d1ab1b250e88df09a to your computer and use it in GitHub Desktop.
Getting count of brands
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
categorySchema.find({}) | |
.exec() | |
.then(categories => { | |
// When you return a promise from a .then callback, the promise that gets returned from the original .then | |
// resolves when the inner promise that you return resolves | |
return Promise.all(categories.map(cat=> { | |
return brandSchema.find({category: cat._id}).count() | |
})); | |
}) | |
.then(counts => { | |
// so this resolves when the Promise.all above resolves | |
// counts is an array of numbers. I don't know what you want to do with them. | |
console.log('DONE'); | |
}); |
Okay thanks! I kinda have started to understand the concept of promises now 👍
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
So what you're asking for is, to a certain extent, simply impossible. It's not that it's impossible to push the results to an array -- it's that it won't matter. You might as well just resolve with the array and then handle it in the callback. It will never be populated synchronously.
What you need is a little less elegant, but inherently no more complicated.