sai
sai

Reputation: 527

How to return responses in nodejs?

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

Answers (3)

Gaurav Varshney
Gaurav Varshney

Reputation: 512

  1. Make call back function as async then use await.

  2. 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

Akash
Akash

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

Corey Calhoun
Corey Calhoun

Reputation: 3

Is the final return in right spot? That's usually what I find I made a mistake.

Upvotes: 0

Related Questions