我有反应原生的组件,显示用户拥有的所有聊天。主逻辑必须在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})
}
);
}
换句话说,主要问题是我不知道如何使用多个回调(用户每次聊天一个)来处理数据结构“聊天”以便最后设置State。也许,我的问题是,我正在以同步方式思考,因为我是一个事件驱动方法的新手。任何帮助表示赞赏。
这是一种可以跟踪剩余请求数量的方法,并在完成后触发一些代码。请注意,这几乎正是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})
}
);
}