In my code, I have a function called installationService.getInstallationMail that retrieves a specific support email from a database.
installationService.getInstallationMail = (id) => {
return cloudant.readDocument(dbInstallations, id)
.then(installation => {
return installation.supportMail;
});
};
Additionally, there is a forEach loop in another function where I check certain properties and if conditions are met, I modify the items and push them to a notifications array:
properties.forEach(item => {
if ((item.value > 0) && ((dateNow - item.value) > dateOneDay)) {
let index = item._id.lastIndexOf("_");
let result = item._id.substr(0, index);
item["baseId"] = result;
let email = installationService.getInstallationMail(item.baseId);
item["supportMail"] = email;
notifications.push(item);
}
});
console.log(notifications);
When I log the notifications array after the loop, it shows that the supportMail property is still pending:
[ { _id: 'id_9oW9i8M9RU_CbT1mKOGPG',
_rev: '26129-6dd842ab825bf291d876486b8157b07b',
control: false,
dataType: 1,
maxValue: '100',
measurable: true,
minValue: '0',
parentId: 'id_9oW9i8M9RU_eFyeP6BmdI',
precision: 2,
propertyType: 7,
value: '1522907022112',
baseId: 'id_9oW9i8M9RU',
supportMail: Promise { <pending> } } ]
I tried using Promise.all inside the loop to wait for the promises to resolve before pushing the items to the notifications array, but it did not work as expected. The goal is to be able to access notifications outside of the forEach loop, but changing the loop to an async function causes the logging to happen prematurely.
If you want to see the full JavaScript code, you can find it here: https://jsbin.com/gujiwatati/edit?js