使用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
相关产品推荐
相关产品推荐

