Taking inspiration from this answer https://stackoverflow.com/a/21571589/9036255 I decided to copy this into my own code. I've found that it doesn't give any response.
function getCallback(callbackTrash) {
var Books = mongoose.model('Book');
Books.find({'username': name[usernames]}, function (err, result) {
callbackTrash(result);
});
}
getCallback(function(result) {
books.push(result);
});
books
is just an array. When I console log it later on, it returns "[]"
If I change books.push
to console.log
, it correctly logs all of the results.
My question is how to get the result to be pushed into the books array?
I have no experience with asynchronous things. What's a practical answer without a steep learning curve?
Here's my greater context:
exports.timeline = function(req, res) {
var Followers = mongoose.model('Follow');
Followers.find({'follower': req.user.username}, function(err, followerResult) {
var name = [req.user.username];
var books = [];
function addName(username) {
name.push(username);
}
for(var user in followerResult) {
addName(followerResult[user]['followed']);
}
for(var usernames in name) {
function getCallback(callbackTrash) {
var Books = mongoose.model('Book');
Books.find({'username': name[usernames]}, function (err, loadOfBollocks) {
callbackTrash(loadOfBollocks);
});
}
getCallback(function(result) {
books.push(result);
});
}
console.log(books);
res.send(books);
});
}