我有以下功能:
installationService.getInstallationMail = (id) => {
return cloudant.readDocument(dbInstallations, id)
.then(installation => {
return installation.supportMail;
});
};
然后我有一个函数,其中有以下 forEach 循环:
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);
console.log 通知返回给我:
[ { _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> } } ]
我现在的问题是,当 Promised 得到解决时,如何在 forEach 循环中推送项目(包括电子邮件)?
我尝试过
Promise.all(email).then(item => {
item["supportMail"] = email;
notifications.push(item);
});
相反,但这也不起作用。
这里重要的是,我想在 forEach
循环之外访问通知
。如果我将 forEach
更改为异步函数,则 notifications
的 console.log 将在循环之前运行。
这是整个 JavaScript 供引用:https://jsbin.com/gujiwatati/edit?js
最佳答案
const notifications = [];
installationService.getInstallationMail = (id) => {
return cloudant.readDocument(dbInstallations, id)
.then(installation => {
return installation.supportMail;
});
};
Promise.all(properties.map((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);
email.then((email) => {
// update item after email resolves
item["supportMail"] = email;
});
notifications.push(item);
// returm email Promise
return email;
}
})).then(() => { // wait for all pending email Promise's to finish
console.log(notifications);
});
您还可以使用await/async
语法
await Promise.all(properties.map(async (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 = await installationService.getInstallationMail(item.baseId);
item["supportMail"] = email;
notifications.push(item);
}
}));
关于javascript - 仅当 Promise 解析时才使用 JS Array.push,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53173214/