简体   繁体   中英

Wait until all the callbacks have been called

I have component in react native that shows all the chats a user has. The main logic must be in componentDidMount(). Here, a simplified version:

componentDidMount(){
     ConnectyCube.chat.list({}, function(error, dialogs) {
        chats = dialogs.map(chat => {
            const opponentId = //some logic
            ConnectyCube.users.get(function(error, res){
                //some logic to populate chats 
            });
            }
        )

        this.setState({chats: chats})
        }
    );
}

Main problem, in other words, is that I don't know how to use multiple callbacks (one for each chat that the user has) to handle the data structure 'chats' in order to setState at the end. Maybe, my problem, is that I'm thinking in a synchronous way because I'm new to an event-driven approach. Any help is appreciated.

Here's a way you can keep track of the number of remaining requests and trigger some code when they are all complete. Note, this is almost exactly what Promise.all does.

//some kind of global or component level variable, tracks the number of pending requests left
var remaining = 0;

componentDidMount(){
     ConnectyCube.chat.list({}, function(error, dialogs) {
        // set remaining to how many dialogs there are
        remaining = dialogs.length;
        chats = dialogs.map(chat => {
            const opponentId = //some logic
            ConnectyCube.users.get(function(error, res){
                //some logic to populate chats

                // decrement remaining and check if we're done
                if (--remaining === 0) {
                  finalCallback(); // in here you do your setState.
                }
            });
            }
        )

        this.setState({chats: chats})
        }
    );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM