ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

JavaScript返回函数发生得太晚

2019-11-10 16:36:13  阅读:184  来源: 互联网

标签:reactjs react-native javascript function


我的代码应该做什么

我正在使用本机反应创建社交媒体应用,但是我的代码遇到了问题.我正在尝试创建一个功能,该功能可捕获所有用户组中的所有帖子.为此,我创建了一个循环.该循环针对用户所在的每个群组重复一次.每个循环都从一个群组获取帖子.每次调用该循环时,都会调用一个新函数,该函数从用户所在的新组中获取帖子,然后将帖子返回到原始函数,从而将其添加到完整的帖子列表中.

问题

获取帖子的功能不会返回帖子.我认为代码不是在等待帖子返回,而是继续前进.基本上,当我用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)) 
      }
    })
  }

标签:reactjs,react-native,javascript,function
来源: https://codeday.me/bug/20191110/2013664.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有