react-native - 异步foreach react-native
问题描述
我正在为移动设备创建一个带有 react-native 和 pouchdb 的聊天应用程序,然后我有一个带有 socket.io 和 rethinkdb 的服务器。在 PouchDB 中,我存储用户之间的所有聊天记录,而在 rethinkdb 中,我存储“离线消息”。对于“离线消息”,我指的是已发送给不在线用户的消息(我在 socket.io 服务器中进行了检查)。
现在我遇到了问题。当我的用户打开应用程序时,我有一个async componentWillMount
这样的:
async componentWillMount(){
const value = await AsyncStorage.getItem("token");
this.setState({ token: value });
var self = this;
await axios.get(server + '/index.php/api/TokenController/isValid', {headers: {Authorization: this.state.token}}).then((res) => {
var resJson = JSON.parse(res.data);
self.setState({userid: resJson.info.id});
});
await axios.get(server + '/index.php/api/FriendsController/getList', {headers: {Authorization: this.state.token}}).then((res) => {
var resJson = JSON.parse(res.data);
this.setState({friends: resJson.friends});
});
this.setState({loading: false});
this.socket.emit('register', {connection_id: this.state.userid});
await this.socket.on('hasMessages', data => Promise.all(data).then(res => {
this.setState({offlineMessages: res});
this.state.offlineMessages.forEach((v) => {
console.log(v) // it stops to first iteration
})
}));
}
所以,用户登录,我检查令牌是否有效,然后我得到了朋友列表。之后,我将我的用户注册到我的 websocket,如果我的用户有消息,我会发送一个“hasMessage”(例如:
{
"from_id": "76" ,
"id": "e5f76ad6-761c-4637-a118-321a844a9634" ,
"messages": {
"1546799624050": "Ciao" ,
"1546799630274": "Hola" ,
"1546799633100": "Hello"
} ,
"to_id": "1"
}
好的,我的用户有一些东西。所以“hasMessage”的响应是这样的。现在我必须做两个循环(一个是关于数据的,另一个是关于每个数据的消息的,我必须为所有消息创建一个消息对象)。我怎样才能做到这一点?我正在使用一个有效的 Promise,但是嵌套的 forEach 在第一次迭代时停止,当我重新加载我的应用程序时,我在控制台中看到其他迭代......一些想法?
我在 async/await/Promise 请求方面不是很好,我只是在学习!
解决方案
推荐阅读
- linux - bash:捕获一个中断并将其“转发”到后台进程
- mongodb - Mongodb Atlas命名约定的问题
- mongodb - React Native 和 MongoDB 领域:找到:带键的对象 {$undefined}
- php - 将购物车中的商品插入数据库表
- java - 如何在 PostgreSQL 中检索两个日期之间的行?
- html - 未捕获的 SecurityError:iFrame 上的 DOMException(代码 18)
- google-chrome-extension - Chrome 未在扩展程序上添加我的自定义 search_provider
- cloud-foundry - Cloud Foundry 中的度量注册器
- python - 匹配两个数据框中的某些列以获得相似度分数
- google-cloud-platform - 谷歌 GCP 云运行 redis 客户端失去与实例的连接