Given an array of Strings that represent item ids, I want to iterate through the strings, pull the item object from my database, and add the item object to an array, that lies outside the scope of the callback from my database.
function getItemObjects(items, callback) {
let returnItems = [];
items.forEach((i) => {
Item.getItemById(i, (err, item) => {
if (err) {
console.log(err);
return;
} else {
returnItems.push(item);
}
});
});
callback(returnItems);
}
Item.getItemById() is a function within my Item model that gets the object from a mongo database. How can I populate an array that's outside the scope of that callback function?
As it stands when I get the callback value from the getItemObjects() function the value is just []. However if I log the value of it within the for loop it is properly populated.