I am creating backend APIs for a Twitter clone. The below API shows the profile of a user. I want to show the tweets of the people that this user is following. But in my response the tweets array is returning an empty array even though I have pushed the data into this array.
Can somebody help me understand why is the tweets array empty in the response?
app.get('/api/profile', auth, function (req, res) {
var email1 = req.user.email;
var followers_data = [];
var tweets = [];
follower.find({ emailoffollowee: email1 }, (err, results) => {
if (err)
console.log(err);
else {
results.map((d, k) => {
followers_data.push(d.emailoffollower);
})
for (var i = 0; i < followers_data.length; i ) {
Tweet.find({ author: followers_data[i] }, (err, results1) => {
if (err)
console.log(err);
else {
results1.map((d, k) => {
tweets.push(d);
})
}
})
}
res.json({
isAuth: true,
id: req.user._id,
email: req.user.email,
name: req.user.firstname req.user.lastname,
followers: followers_data,
tweet: tweets
});
}
})
.catch(error => {
console.log(error);
})
});```
CodePudding user response:
You Have Tweet.find()
which is an asynchronous function, to resolve the problem I used async/await
app.get('/api/profile', auth, function (req, res) {
var email1 = req.user.email;
var followers_data = [];
var tweets = [];
follower.find({ emailoffollowee: email1 }, async (err, results) => {
if (err)
console.log(err);
else {
results.map((d, k) => {
followers_data.push(d.emailoffollower);
})
for (var i = 0; i < followers_data.length; i ) {
let results1 = await Tweet.find({ author: followers_data[i] });
results1.map((d, k) => {
tweets.push(d);
})
}
res.json({
isAuth: true,
id: req.user._id,
email: req.user.email,
name: req.user.firstname req.user.lastname,
followers: followers_data,
tweet: tweets
});
}
})
.catch(error => {
console.log(error);
})
});
I recommend you to read this article async/await