Reputation: 43
I want to know if a user liked a book and display a heart depending on the state (liked/ not liked) in the results in my view.
The problem is that the value from the second query is not available outside of that function.
I tried using a async function inside but that gives back no result. I also tried adding the books to an array and return that, this gives an empty array.
var bookQuery = Book.find({ title: req.body.title}, {}, { skip: 0, limit: 200 })
.sort({ name: 1 });
bookQuery.lean().exec(function (err, books) {
books = books.map(function (book) {
Like.findOne({ object: book._id, likedby: req.session.passport.user }).exec(function (err, like) {
book.liked = (like != null) ? 1 : 0;
// Here it's available
});
return book;
});
cb(books);
}, cb);
I want to add a field for each book with the value from the Like query. Right now it only displays the books.
Upvotes: 0
Views: 93
Reputation: 723
So as you know a lot of things are async in Node JS, you are not able to get the result from outside of the callback function. For callbacks, you can just use async module in order to avoid callback hells. async module is very popular among Node JS developers so if you use callbacks, I strongly recommend to use async. It has dozens of methods which facilitate and flourish your code.
However, with ES6 comes a lot of new and helpful functions. One of these functions is Promise. It is developed based on callbacks and it makes easy to code async functions. There is also one easy way to overcome asynchronous functions is async/await. Actually, there are generator functions.
Upvotes: 1