等到所有回调都被调用



我在react Native中具有组件,该组件显示了用户拥有的所有聊天。主要逻辑必须在componentDidmount()中。在这里,简化版本:

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})
        }
    );
}

主要问题,换句话说,我不知道如何使用多个回调(用户拥有的每个聊天)来处理数据结构"聊天"以便在末尾设置。也许,我的问题是,我以同步的方式思考,因为我是事件驱动的方法的新手。任何帮助都将不胜感激。

这是一种方法,您可以跟踪剩余请求的数量并在完成时触发一些代码。请注意,这几乎是Promise.All所做的。

//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})
        }
    );
}

最新更新