Reputation: 90
User.find().then(function (user) {
console.log(user)
})
Category.find().then(function (category) {
console.log(err);
})
Content.find().then(function (content) {
console.log(content);
})
how can I combine the query sentences into one and get all result? ps: I use mongoose to operation mongoDb.
Upvotes: 6
Views: 5800
Reputation: 588
You can wrap all of your queries inside Promise.all() to get the desired result. The queries passed to Promise.all() will be executed concurrently. Check out the code below.
Promise.all([
User.find(),
Category.find(),
Content.find()
])
.then(results=>{
//results return an array
const [users,categories,content] = results;
console.log("users",users);
console.log("categories",categories);
console.log("contents",content);
})
.catch(err=>{
console.error("Something went wrong",err);
})
In case you are using bluebird library then you can use Promise.props(), which basically allows you to pass an object instead of an array.
Promise.props({
users:User.find(),
categories : Category.find(),
content : Content.find()
}).then(result=>{
console.log("users",result.users);
console.log("categories",result.categories);
console.log("contents",result.content);
}).catch(err=>{
console.error("Something went wrong",err);
})
Upvotes: 10