Reputation: 527
I have below code:
exports.generateCo = async function(req,res,next){
//some code
return new Promise(function (resolve,reject){
if(err){
//some code
}
else{
//some code
let mail = await sendEmail.otp(val,mailid,sub);
console.log("mail -- ",mail);
}
})
}
In Another file:
exports.otp = async function(val,mailid,sub){
//some code
transporter.sendMail(options,(error,info) =>
if(error){
//error logs
respobj = {status: "err"};
}
else{
//success logs
respobj = {status: "success"};
}
return respobj;
}
Here in the first file, Im not able to get the response in "mail" variable. Im getting "undefined" value. Can anybody please help me with this?
Upvotes: 1
Views: 89
Reputation: 512
Make call back function as async then use await.
Return respobj from with in call back, if you try to return the response from outside of the callback then before waiting for any transporter.sendMail it will return undefined.
exports.generateCo = async function(req,res,next){
//some code
return new Promise(async function (resolve,reject){
if(err){
//some code
}
else{
//some code
let mail = await sendEmail.otp(val,mailid,sub);
console.log("mail -- ",mail);
}})
}
exports.otp = async function(val,mailid,sub){
//some code
transporter.sendMail(options,(error,info) => {
if(error){
//error logs
respobj = {status: "err"};
}
else{
//success logs
respobj = {status: "success"};
};
return respobj});
}
Upvotes: 0
Reputation: 4553
The
await
wont work inside a promise.
As per the given code,you do not need to define a new promise inside the async function.
If you need the new promise, you cannot you the await inside a promise callback. You should the then format instead.
sendEmail.otp(val,mailid,sub).then((mail) => {
console.log("mail -- ",mail);
})
Also, the otp function has a callbck, so it has to be wrapped in a promise.
exports.otp = async function(val,mailid,sub) {
//some code
return new Promise((resolve, reject) = {
transporter.sendMail(options,(error,info) => {
if(error){
//error logs
respobj = {status: "err"};
} else {
//success logs
respobj = {status: "success"};
}
return resolve(respobj);
})
})
}
Upvotes: 1
Reputation: 3
Is the final return in right spot? That's usually what I find I made a mistake.
Upvotes: 0