2👍
✅
Try storing all the promises on an array, and then calling the Promise.all() method on it. This is like a wrapper for a set of promises, that executes the callback as soon as all promises are executed.
If you like this approach, your code would look something like this:
asyncData({ params }) {
var postRef = Firestore.collection('posts').doc(params.post);
var commentRef =
Firestore.collection('posts').doc(params.post).collection('comments');
return commentRef.orderBy('created_on', 'desc').get().then(snapshot => {
var comments = []
snapshot.forEach(doc => {
var docData = doc.data()
comments.push({
comment: { data: doc.data(), id: doc.id }
})
})
return comments
})
.then(data => {
var comments = []
// Declare an empty array, where we'll store all the promises
var promises = []
for (const comment of data) {
let promise = Firestore.collection('users-public').doc(comment.comment.data.created_by).get()
// Push the promise to the array
promises.push(promise)
}
// Callback on this method will execute once all promises on array have been resolved
Promise.all(promises).then(users => {
console.log("All users fetched!")
// users is an array with every promise result for every user query
users.forEach(user => {
let userId = result.id
// Attach user to every comment owned by him
comments.filter(comment => {
return comment.comment.data.created_by === userId
}).map(comment => {
comment.user = user.data()
})
})
console.log("Returning!")
return { comments: comments }
})
})
}
As an alternative, you can use a library like async to handle flow from asynchronous functions.
Hope this helps!
Source:stackexchange.com