I want to run code in a .then()
after a fetch()
resolves, the issue is that my .then()
does not run after the POST
method resolves, it does however if it rejects.
What I am doing is sending a mail through my server using Nodemailer. So I’m not entirely sure what the issue is but perhaps Nodemailer doesn’t return a promise to the call or it takes too long and therefore it only runs .then()
if it rejects. Does anyone know what the issue is and how it can be solved or perhaps if there are alternative ways that I can run some code after the fetch()
has resolved?
Form submission:
const handleSubmit = (e) => { e.preventDefault(); fetch("http://localhost:4000/send_mail", { method: 'POST', body: formData }).then((res) => { //This does not run on resolve if (res.ok) { } }); }
Server:
app.post("/send_mail", cors(), async (req, res) => { await transport.sendMail({ from: sender, to: receiver, subject: "Subject", html: ``, attachments: [{ filename: filename, content: content } }) });
Advertisement
Answer
Send a response from your server:
transport.sendMail({ // mailoptions }, (err, data) => { if (err) { console.log(err); res.status(400).send('Error'); } else { res.status(200).send('Success'); } })