This is the first time I am posting here :)
I have a task at hand which involves looping through keys of an object using a forEach() loop and then pushing specific values into an array for each element. After completing the loop, I need to resolve the array containing all the pushed values.
From what I gather, fetching values outside the context of the forEach() loop can be tricky. Is there a way to achieve this?
Below is a snippet of the code that illustrates what I am trying to accomplish:
some function returning a promise
...
...
let promisesArray = [];
//Iterating over each object in the data array
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
Currently, it is returning an empty array.
The desired output should look something like this instead:
[
'Object: key1 | someOtherKey1',
'Object: key2 | someOtherKey2',
'Object: key3 | someOtherKey3',
...
]
Thank you in advance for your insights!