我的代码应该做什么
我正在使用本机反应创建社交媒体应用,但是我的代码遇到了问题.我正在尝试创建一个功能,该功能可捕获所有用户组中的所有帖子.为此,我创建了一个循环.该循环针对用户所在的每个群组重复一次.每个循环都从一个群组获取帖子.每次调用该循环时,都会调用一个新函数,该函数从用户所在的新组中获取帖子,然后将帖子返回到原始函数,从而将其添加到完整的帖子列表中.
问题
获取帖子的功能不会返回帖子.我认为代码不是在等待帖子返回,而是继续前进.基本上,当我用console.log记录获得该功能的帖子时,会得到正确的帖子,但是当我用console.log记录整个帖子列表时,我什么也得不到.
我的问题
我如何等待函数返回一个值,而又不让代码立即继续运行?
我的密码
runQ(group){
//this function actually gets the posts from the server (from firebase)
var items = [];
firebase.database().ref('posts/'+group).limitToLast(
Math.floor(24/this.state.passGroups.length)*this.state.numOfPosts
).orderByKey().once ('value', (snap) => {
snap.forEach ( (child) => {
items.push({
//post info
});
});
this.setState({passItems: items})
console.log(items); //logs correct items.
}).then(()=>{
if( this.state.passItems.length != 0 ){return this.state.passItems;}
})
}
//gets the user's groups, then sends out a request to each group for the newest posts.
getItems(){
//gets groups...
//...
.then(()=>{
var allItems = [];
//allItems will be the big list of all of the posts.
for (i = 0; i < this.state.passGroups.length; i++) {
//sending request to runQ function to get posts.
allItems.push(this.runQ(this.state.passGroups[i].name)) //allItems logs as allItems: ,,,,
}
})
}
解决方法:
使用async-await使for循环等待每个响应.
首先,您需要返回由Firebase调用创建的Promise(您目前不从runQ()函数返回任何内容).
更改此行:
firebase.database().ref('posts/'+group).limitToLast(
变成:
return firebase.database().ref('posts/'+group).limitToLast(
然后告诉您对getItems()调用的回调是一个异步函数,并等待来自runQ()的每个响应:
getItems(){
//gets groups...
//...
.then(async () => {
var allItems = [];
for (var i = 0; i < this.state.passGroups.length; i++) {
allItems.push(await this.runQ(this.state.passGroups[i].name))
}
})
}