This is my first post ever :)
So what I am trying to do is loop through keys of an object with a forEach() loop and for each element, push specific values into an array. Then after the loop, resolve the array containing all pushed values.
As I understand, it's hard to get out values of the forEach() context. Is there a way to do something like that ?
Here's a code exemple of what I'm trying to do:
some function returning a promise
...
...
let promisesArray = [];
//Loop on each object from data and do whatever
ObjectJSON.array.forEach((object) => {
if (object.key === "foo") {
functionBar()
.then((response) => {
promisesArray.push(
`Object: ${object.key} | ${object.someOtherKey}`
);
})
.catch((error) => {
reject(error);
});
}
});
resolve(promisesArray);
}); //end of promise's return
Right now, it returns an empty array.
The expected result should be something like this instead:
[
'Object: key1 | someOtherKey1',
'Object: key2 | someOtherKey2',
'Object: key3 | someOtherKey3',
...
]
Thanks a lot for your answers !
CodePudding user response:
Congrats on your first post ever!
It's a super classic question though, how to use an asynchronous function in a loop. With .forEach you can't, but you can using await in a for loop :
let promisesArray = [];
for (let object of ObjectJSON.array) {
if (object.key !== "foo") continue;
const response = await functionBar();
promisesArray.push(
`Object: ${object.key} | ${object.someOtherKey}`
);
}
resolve(promisesArray);
Using await will probably require your function to be marked as async (async function doSomething() { ... )
