-1
export function RecommendList(data) {
    return (dispatch, getState) => {
        let db = loadFB().firestore();
        let query = db.collection('users').where("recommend", ">", "0").orderBy("recommend", "asc")
        let user_list = []; 
        let uid_arr=[];
        let result = [];
        query.get().then(async docs => {
            docs.forEach(doc => {
                const recommender = doc.data();
                const recommend_id = recommender.recommend;
                const recommend_person = recommender.displayName;                                
                user_list.push({id : recommend_id, recommend_person : recommend_person });
            })        

            uid_arr = getRecommendList(user_list);

            console.log("getRecommendList",uid_arr);

            for(let i = 0; i < uid_arr.length; i++) {
                const user_doc = await db.collection('users').doc(uid_arr[i].id).get();
                console.log(user_doc.data());
                let user_info = user_doc.data()
                user_info.betball_dupli_count = uid_arr[i].count;
                user_info.recommend_person = uid_arr[i].person;
                console.log('displayname' , user_info.displayName , 'betball count',user_info.betball_dupli_count,'person',user_info.recommend_person);
                result.push(user_info);
            } 
            console.log('result!', result);
            dispatch({
                type: types.SET_USER_LIST,
                data: result,
                page: 1
            })
        })
    }
}


I work on importing data from the Fire Store and sending it to the dispatch. By the way, I want to make a code that increases the efficiency of this work by asynchronous mode in javascript. I'd like to know how to wait and process a form asynchronously.

In short, how to turn "for" of this code into async mode!

hoon3024
  • 27
  • 5

1 Answers1

3

With minimal changes to your existing code:

let userQueries = [];
for (let i = 0; i < uid_arr.length; i++) {
    userQueries.push(
        db.collection('users').doc(uid_arr[i].id).get()
        .then(user_doc => {
            console.log(user_doc.data());
            let user_info = user_doc.data()
            user_info.betball_dupli_count = uid_arr[i].count;
            user_info.recommend_person = uid_arr[i].person;
            console.log('displayname', user_info.displayName, 'betball count', user_info.betball_dupli_count, 'person', user_info.recommend_person);
            result.push(user_info);

        })
    )
}
await Promise.all(userQueries);

The outer for loop will just initiate the queries and the then part of each one will run when the specific query is complete. Outside of the for loop, the Promise.all call will wait for all of the queries to complete before continuing.

igg
  • 2,172
  • 3
  • 10
  • 33