Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

javascript - Return array of data from firestore query

I want to retrieve information of all the users who are friends of a particular user. To return a single json array I am pushing data first to an array and then returning the data but looks like data is returning empty due to asynchronous behavior of firestore queries. Can anyone please help how to return data after all values get pushed to it.

export async function getUserFriendsDetails(userId) {
    var data = {
        results: []
    }
    getUser(userId).then((snapshot) => {
        snapshot.data().friends.forEach(friend => {
            getUserDetails(friend).then((result) => {
                data.results.push(result.data()) // data is getting pushed here
            })
        })
    })
    return data;  // data is empty array here
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

We can use a callback to return once the entire data is populated.

export async function getUserFriendsDetails(userId) {
    var data = {
        results: []
    }
    getUser(userId).then((snapshot) => {
        snapshot.data().friends.forEach(friend => {
            getUserDetails(friend).then((result) => {
                data.results.push(result.data()) // data is getting pushed here
            })
        },function(data){
          alert(data);// Entire data
          })
    })
    return data;  // data is empty array here
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...