仅当Promise解决时,JS Array.push

时间:2018-11-06 13:46:34

标签: javascript arrays asynchronous promise

我具有以下功能:

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> } } ]

我的问题是,当“承诺”解决后,如何在forEach循环中推送项目(包括电子邮件)?

我尝试过

Promise.all(email).then(item => {
  item["supportMail"] = email; 
  notifications.push(item);
});

相反,但这也不起作用。

这里重要的是,我想在notifications循环之外访问forEach。如果我将forEach更改为异步功能,则notifications的console.log在循环之前运行。

这是供参考的完整JavaScript:https://jsbin.com/gujiwatati/edit?js

2 个答案:

答案 0 :(得分:1)

function Test = props => {
  const { text } = props;
     return(
       <div>
          <h1>{text}</h1>
       </div>
     )
}

您还可以使用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

答案 1 :(得分:0)

您的功能installationService.getInstallationMail返回的不是您期望的字符串,您收到的是承诺cloudant.readDocument返回。我建议您执行以下操作:

installationService.getInstallationMail = (id) => {
  let promise = Promise();
  cloudant.readDocument(dbInstallations, id)
    .then(installation => {
      promise.resolve(installation.supportMail);
      return;
    });
  return promise;
};
let emailPromise = installationService.getInstallationMail(item.baseId);
emailPromise.then(email => {
  item["supportMail"] = email;
  notifications.push(item);
  console.log(item);
})