У вас есть две проблемы в этом коде:
1) Для свойства sendMail
поддерживаются типы string | string[]
.
Т.е. вы можете отправить "a@domain, b@domain"
или ["a@domain", "b@domain"]
,
Возвращаемое значение
EmpList.findOne({attributes:['profEmail'],where:{firstName: reportTo}});
равно promise<pending>
, поскольку вы не ожидаете результата. Вы фактически назначаете to
на: Promise<pending>
, который не является: string | string[]
.
Если вы будете использовать функцию async
, вы можете сделать:
const emp = await EmpList.findOne({attributes:['profEmail'],where:{firstName: reportTo}})
transporter.sendMail({
to: emp,
from: 'CTHRM@coretechies.com,',
subject: 'You recieved a user request',
html: `<p>please check your app to take action on this request</p>`
});
res.status(201).json({message: 'leave updated', userId: result.id, status: '1'})
и затем присвойте res
to
свойству sendMail
2) sendMail
также возвращает обещание, так что вы должны дождаться результата обещания и поймать ошибку, если она была выдана:
transporter.sendMail({
to: EmpList.findOne({attributes:['profEmail'],where:{firstName: reportTo}}),
from: 'CTHRM@coretechies.com,',
subject: 'You recieved a user request',
html: `<p>please check your app to take action on this request</p>`
})
.then((data) => conosle.log(data))
.catch((e) => console.error(e);
Вот почему вы получаете:
(узел: 9440) UnhandledPromiseRejectionWarning: необработанное отклонение обещания. Эта ошибка возникла либо из-за того, что внутри асинхронной функции возникла ошибка без блока catch, либо из-за отклонения обещания, которое не было обработано с помощью .catch (). (идентификатор отклонения: 1) (узел: 9440) [DEP0018] Предупреждение об устаревании: отклонения необработанного обещания устарели. В будущем отклонения обещаний, которые не обрабатываются, завершат процесс Node.js с ненулевым кодом завершения.
EDIT :
Полный пример с функцией асин c. предположим, что весь этот код написан под функцией, предположим, что эта функция называется create
.
async function create(req, res, next) {
try {
let leaveRes = await Leave.create({
leaveType: leaveType,
fromDate: fromDate,
toDate: toDate,
emailId: emailId,
reason: reason,
reportTo: reportTo,
userId: userId
});
let leaveReqRes = await LeaveReq.create({
empName: userId,
appliedFrom: fromDate,
apliedTo: toDate,
leaveType: leaveType,
status: req.body.status,
reqTo: reportTo
});
const emp = await findEmp({firstName: reportTo});
await sendMailToEmp(emp);
// If you made it to here, everything succeeded.
res.status(201).json({message: 'leave updated', userId: result.id, status: '1'});
} catch(e) {
console.error('Problem in executing create', e);
throw e; // or next (e) depends on how it is built.
}
}
function findEmp(filter) {
return EmpList.findOne({
attributes:['profEmail'],
where: filter
});
}
function sendEmailToEmp(emp) {
try {
transporter.sendMail({
to: emp,
from: 'CTHRM@coretechies.com,',
subject: 'You recieved a user request',
html: `<p>please check your app to take action on this request</p>`
});
} catch(e) {
console.error('Problem in sending mail', e);
}
}