You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Fastify时,如何通过Nodemailer异步返回API响应?遇TypeError问题

Fastify中正确处理Nodemailer sendMail的异步响应

你出错的核心原因是混合使用了await和.then():当你用await调用transporter.sendMail时,变量a已经是该方法执行后的最终结果(不是Promise对象),所以它没有.then()方法,才会抛出TypeError: a.then is not a function。

下面是两种正确的写法,任选其一即可:

方法一:使用await + try/catch(推荐)

这种写法更符合现代异步代码风格,也能更好地和Fastify的异步路由兼容:

try {
  const result = await transporter.sendMail(mainOptions);
  reply.send({
    messageId: result.messageId
  });
} catch (error) {
  // 处理邮件发送失败的情况,返回错误响应
  reply.code(500).send({ error: error.message });
}

transporter.sendMail本身支持Promise,await会等待它执行完成:成功时直接拿到结果,失败时进入catch块捕获错误。Fastify会自动等待async路由函数中的异步操作完成,不会提前返回响应。

方法二:直接使用Promise的then/catch

如果你习惯链式调用的写法,也可以直接用Promise的回调:

transporter.sendMail(mainOptions)
  .then(result => {
    reply.send({
      messageId: result.messageId
    });
  })
  .catch(error => {
    reply.code(500).send({ error: error.message });
  });

这种写法下,Fastify会识别到返回的Promise,自动等待它执行完成后再处理响应。

注意:不要同时混用await和.then(),这是引发错误的关键。

内容的提问来源于stack exchange,提问作者user21276931

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 23:42:27