I am trying to push to an array inside a nested forEach loop in JavaScript yet to no avail. I have tried cloning the array and appending to it but doesn't seem to work for me. below is my code. any help would be hugely appreciated. thanks in advance.
const trollImgIds = ["61c25b801957f9eb4f5c2a94", "61c25b801957f9eb4f5c2a95"];
const images:any = [];
trollImgIds.forEach((trollImgId:any) => {
const imgIds = trollImgId.imgIds;
imgIds.forEach(async (imgId:any) => {
const _id = new mongoose.Types.ObjectId(imgId);
imgGfs.find({ _id: _id }).toArray((err:any, files:any) => {
if(err){
console.log(err);
}
if(files.length > 0){
const image:any = [];
// open download stream and add images to the images array
const readstream = imgGfs.openDownloadStream(_id);
// read buffer using stream
readstream.on('data', (chunk:any) => {
image.push(chunk);
});
readstream.on('error', () => {
console.log('error');
});
readstream.on('end', () => {
// convert buffer to bufferlist
const bufferList = new BufferList(image);
// convert the bufferlist to base64 string
const base64 = bufferList.toString('base64');
// add to images array
// console.log("image >>> : ", base64);
// clone and add to images array
const trollImage = {
trollId: trollImgId.id,
image: base64
}
// clone the images array
const cloneImages = [...images];
// add the troll image to the images array
cloneImages.push(trollImage);
// set the images array
images.push(cloneImages);
});
}
});
});
});
I was expecting to get an output like:
images >>> : [
{
trollId: new ObjectId("61c25b801957f9eb4f5c2a94"),
image: '/9j/4AAQSkZJRgABAQEAYABgAAD/...'
}
]
which is the case when I log it inside the second forEach loop however it turns out to be empty outside the loops