I have the following function for sending emails using the nodemailer and a HapiJS server:
let data = request.payload;
if (data.file) {
let name = data.file.hapi.filename;
let caminho = __dirname + "/uploads/" + name;
let file = fs.createWriteStream(caminho);
file.on('error', function (err) {
console.error(err)
});
data.file.pipe(file);
data.file.on('end', function (err) {
mailOptios.attachments.push({
filename: name,
path: caminho //push nos anexos quando o upload está concluido
});
reply('Upload Concluído');
});
}
let destinatario = '[email protected]';
let ass = 'teste com anexo';
let email = 'Teste com anexo';
let mailOptios = {
from: usuario, //usuário está definido mais acima no código
to: destinatario, //não incluí usuário aqui por questões de privacidade
subject: ass,
text: email,
attachments: [
]
};
console.log(mailOptios);
transporter.sendMail(mailOptios, function (err, info) {
if (err){
console.log(err)
} else {
console.log('Enviado! ' + info.response);
return reply.response('Enviou')
}
})
However, the process is occurring asynchronously and the email is being sent before the full attachment upload occurs.
How do you leave this function synchronous or make sure the attachment is ready before sending the email?