1

I need use an array of Parse.User objectId's from Parse Platform to fetch this users and save a Parse Object called 'Project' with a column 'Gestor' that have the users who are managers of the project saved.

That is my array:

data.gestor = [
  "riid9e82uA",
  "tYxICE1ZOf",
  "MXYSc0iiYK"
]

There is my function:

let gestors = [];
await data.gestor.forEach(async (value) => {
    console.log(value);
    let userQuery = new Parse.Query(Parse.User);
    userQuery.equalTo('objectId', value);
    let newGestor = await userQuery.first();
    console.log(JSON.stringify(newGestor, null, 2));
    await gestors.push(newGestor);
})
console.log(JSON.stringify(gestors, null, 2));

On the console output I have the Id's, after the code first print the array gestors empty, so I have the objects that I print on console.log() into forEach:

riid9e82uA
aw6cjLgajN
tYxICE1ZOf
[]
{
  "username": "teste123@email.com",
  "firstName": "ola",
  "lastName": "adeus",
  "emailVerified": false,
.
.
.
"tYxICE1ZOf": {
      "read": true,
      "write": true
    }
  },
  "objectId": "tYxICE1ZOf"
}

Why the code executes first the third console.log() before the second into the forEach and how I can push the objects into an array and after use this array correctly populated to create my new Object?

ChristianYami
  • 586
  • 1
  • 9
  • 17
Philippe
  • 31
  • 7

2 Answers2

0

Usage of async/await inside forEach is a little bit tricky.

You can create your own forEach function:

async function asyncForEach(array, callback) {
  for (let index = 0; index < array.length; index++) {
    await callback(array[index], index, array);
  }
}

Then you can adjust your code:

let gestors = [];
await asyncForEach(data.gestor, async (value) => {
    console.log(value);
    let userQuery = new Parse.Query(Parse.User);
    userQuery.equalTo('objectId', value);
    let newGestor = await userQuery.first();
    console.log(JSON.stringify(newGestor, null, 2));
    await gestors.push(newGestor);
})
console.log(JSON.stringify(gestors, null, 2));

Source: https://codeburst.io/javascript-async-await-with-foreach-b6ba62bbf404

Let me know if it works!

Szymek
  • 163
  • 1
  • 9
  • Yeah, I solved creating another function do to the loop, but using for...of like I showed on my answer here. – Philippe Dec 16 '20 at 12:20
0

Worked pretty well the answer on Using async/await with a forEach loop using for ... of like that:

let gestors = [];
async function getGestors (gestores) {
    for (const gestor of gestores) {
       let userQuery = new Parse.Query(Parse.User);
       userQuery.equalTo('objectId', gestor);
       let newGestor = await userQuery.first();
       gestors.push(newGestor);
    }
}
await getGestors(data.gestor);
console.log(JSON.stringify(gestors, null, 2));

Now I have the output as expected and I am saving correctly an array of Parse.User on my new Object.

Should I keep this topic or remove because another topic has the solution?

Philippe
  • 31
  • 7