【问题标题】:How to use map inside try/catch?如何在 try/catch 中使用 map?
【发布时间】:2021-04-22 15:22:23
【问题描述】:

我有一个样品,请看一下,如果我做对了,

export const create = async ({ invitationList, testId }) => {
  try {
    const promises = invitationList.map(async invitationTo => {
      return new Promise(async (resolve, reject) => {
        const invitation = await InterviewSchedule({
          invitationTo,
          testId
        }).save();
        resolve(invitation);
      });
    });
    Promise.all(promises).then(value => {
      console.log(value);
    });
  } catch (error) {
    throw error;
  }
};

我无法在 catch 块中捕获错误。

【问题讨论】:

标签: javascript node.js promise async-await


【解决方案1】:

经典的 try/catch 错误控制流仅在您 await 承诺时才有效。在您的代码中,您无需等待Promise.all。试试这个:

export const create = async({
  invitationList,
  testId
}) => {
  try {
    const promises = invitationList.map(invitationTo =>
        new InterviewSchedule({
          invitationTo,
          testId
        }).save());
    const results = await Promise.all(promises);
    console.log(results);
  } catch (error) {
    throw error;
  }
};

【讨论】:

  • 我喜欢你的方式,假设我想不等待就发送邮件
  • 您的意思是发邮件以防出错?
  • 不不,我想在创建面试后,在 try 块内发送邮件
  • 哦,好吧,然后像这样链接另一个Promisenew InterviewSchedule(...).save().then(sendMail) 假设sendMail 是一个function,它返回一个Promise
  • @GuerricP 不是then。把它放在你已经拥有的await 之后。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-15
  • 2012-11-25
  • 1970-01-01
  • 1970-01-01
  • 2011-07-12
  • 1970-01-01
相关资源
最近更新 更多