英文:
async nodemailer sendmail Promise
问题
如何获得一个 'then',或者异步返回一个 API 响应?
我使用 fastify,但如果在其中进行回调,它不会等待响应。
我尝试过这样做,但出现错误:TypeError: a.then is not a function
。
const a = await transporter.sendMail(mainOptions);
a.then((error, result) => {
if (error) return error
reply.send({
messageId: result.messageId
})
})
英文:
how can I get a 'then', or asynchronously return an API response?<br>
I use fastify, but it doesn't wait for a response if you make a callback inside.<br>
I tried that, but the error: TypeError: a.then is not a function
<br>
const a = await transporter.sendMail(mainOptions);
a.then((error, result) => {
if (error) return error
reply.send({
messageId: result.messageId
})
})
答案1
得分: 0
以下是翻译好的部分:
简单记录 a
:
const a = await transporter.sendMail(mainOptions);
console.log(a)
您还可以使用 try/catch
捕获错误:
try {
const a = await transporter.sendMail(mainOptions);
console.log(a)
reply.send({ messageId: result.messageId })
} catch (error) {
console.error(error)
}
看起来您正在尝试使用 nodemailer 发送电子邮件。您是否尝试遵循文档:
transporter.sendMail({
from: 'sender@example.com',
to: 'recipient@example.com',
subject: 'Message',
text: 'I hope this message gets delivered!'
}, (err, info) => {
console.log(info.envelope);
console.log(info.messageId);
});
英文:
Simply log a
:
const a = await transporter.sendMail(mainOptions);
console.log(a)
You can also catch the error with a try/catch
try {
const a = await transporter.sendMail(mainOptions);
console.log(a)
reply.send({ messageId: result.messageId })
} catch (error) {
console.error(error)
}
Looks like you are trying to send email with nodemailer. Have you tried to follow the documentation:
transporter.sendMail({
from: 'sender@example.com',
to: 'recipient@example.com',
subject: 'Message',
text: 'I hope this message gets delivered!'
}, (err, info) => {
console.log(info.envelope);
console.log(info.messageId);
});
答案2
得分: 0
请参考以下翻译的代码部分:
你应该提到完整的方法/服务逻辑以便为你提供更好的解决方案!不过,试试这个:
- 确保安装 nodemailer 类型 `npm i @types/nodemailer`
- 你已经在等待 transporter 发送电子邮件,不需要使用 `then()` 方法,而是尝试这样:
```typescript
try {
const a = await transporter.sendMail(mainOptions);
if (a.error) {
throw a.error;
}
reply.send({ messageId: a.result.messageId });
} catch (error) {
// 处理错误
console.error(error);
}
<details>
<summary>英文:</summary>
You should mention the full method/service logic to give you a better solution! however, try this:
- be sure to install nodemailer types `npm i @types/nodemailer`
- you already awaiting transporter to send email, there is no need for `then()` method, try this instead:
```typescript
try {
const a = await transporter.sendMail(mainOptions);
if (a.error) {
throw a.error;
}
reply.send({ messageId: a.result.messageId });
} catch (error) {
// Handle error
console.error(error);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论