i just recently try learn nodejs, i choose adonisjs framework, because i think it's will be easier for me to learn, because on the nutshell have some similarities with laravel, which i used to code with.
but now, i have some problem, i can't solve, i have function like this :
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)
}
when i run this function, it's show an empty array []
, i know because of nodejs or js actually have asynchronous behavior, it run this : console.log(myArray)
first
what i expected is, how to execute, or return myArray
after all the looping or other process is done?
-- problem is on the way i loop the array is not on the way i made callback, promise, because i already using async - await
which is returning promise and it's behavior. map
or forEach
does not allow what i expected.. and the solution is clear : for ( item of items )
thank you
答案 0 :(得分:1)
实际上我刚刚找到了解决方案,对于那个告诉我的其他地方的人来说,我不能使用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
}
每次都在工作.. !!