代码之家  ›  专栏  ›  技术社区  ›  vidihermes

运行foreach后返回变量

  •  1
  • vidihermes  · 技术社区  · 7 年前

    我最近试着学习nodejs,我选择了adonisjs框架,因为我认为它对我来说更容易学习,因为简单来说,它与我以前编写代码的laravel有一些相似之处。

    但现在,我有一些问题,我无法解决,我有这样的功能:

      async getAllPeople() {
        let allPeople = await People.all()
        let myArray = []
        let checkChild = async (people) => {
          let eachPeopleChild = await people.children().fetch()
          if (eachPeopleChild.rows.length > 0) {
            return people
          }
          return false
        }
        allPeople.rows.forEach(async (people) => {
          let res = await checkChild(people)
          if (res !== false) {
            myArray.push(res)
          }
        })
        console.log(myArray)
      }
    

    当我运行这个函数时,它显示一个空数组 [] ,我知道因为nodejs或js实际上有异步行为,所以它运行如下: console.log(myArray) 第一

    我期望的是,如何执行或返回 myArray 在所有的循环或其他过程完成之后?

    --问题是在我循环数组的过程中,数组不在我进行回调的过程中,promise,因为我已经在使用 async - await 这是对承诺和行为的回报。 map forEach 不允许我所期望的…解决办法很明确: for ( item of items )

    谢谢您

    1 回复  |  直到 7 年前
        1
  •  1
  •   vidihermes    7 年前

    事实上我刚刚找到了解决办法,那个在另一个地方告诉我,我不能用的人 forEach 只是使用 for (let item of anArray) 相反。 这是我的代码:

      async getAllPeople() {
        let allPeople = await People.all()
        let myArray = []
        let checkChild = async (people) => {
          let eachPeopleChild = await people.children().fetch()
          if (eachPeopleChild.rows.length > 0) {
            return people
          }
          return false
        }
    
        for (let people of allPeople.rows) {
          let res = await checkChild(people)
          if (res !== false) {
            myArray.push(res)
          }
        }
        return myArray
      }
    

    现在一切都正常了!!