Reputation: 1984
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.
Upvotes: 3
Views: 244
Reputation: 385
You can use promises to extract the values from the database callback.
try this:
function getItemObjects(items, callback) {
const itemPromises = items.map((itemId) => {
return new Promise((resolve, reject) => {
Item.getItemById(itemId, (err, item) => {
if (err) {
reject(err);
}
resolve(item);
});
});
});
Promise.all(itemPromises)
.then(results => callback(results))
.catch(error => callback(error));
}
Pay attention here, if any of the items results in an error, then the whole promise (from Promise.all) will fail and the catch block will be executed.
You can find more on Promise.all and Promise.catch
Upvotes: 2