0

What would be the best way to call a function from another file and then do something else if the first function is done and returns true?

module.exports = {
  sendEmail: function(user, subject, text) {
    var smtpTransport = nodemailer.createTransport({
      service: 'gmail',
      auth: {
        user: config.email,
        pass: config.gmlpwd
      }
    });
    var mailOptions = {
      to: user,
      from: config.email,
      subject: subject,
      text: text
    };
    smtpTransport.sendMail(mailOptions, function(err) {
      return true
    });
  }
}
mailer.sendEmail(user.email, subject, text, function(){
     //do something here if the function is done successfully, but it never gets called
});
sh1hab
  • 661
  • 5
  • 16
Jan
  • 653
  • 1
  • 7
  • 22

3 Answers3

1

Inside of your sendMail function, you need to add that callback as an argument and then call it when you are done.

module.exports = {
  sendEmail: function(user, subject, text, cb) {
    var smtpTransport = nodemailer.createTransport({
      service: 'gmail',
      auth: {
        user: config.email,
        pass: config.gmlpwd
      }
    });
    var mailOptions = {
      to: user,
      from: config.email,
      subject: subject,
      text: text
    };
    smtpTransport.sendMail(mailOptions, function(err) {
      return cb(err);
    });
  }
}
mailer.sendEmail(user.email, subject, text, function(){
     // do something here
});

However, doing this repeatedly will probably lead you into callback hell, I would suggest looking into using Promises or RxJS instead.

laptou
  • 6,389
  • 2
  • 28
  • 59
1
      <!-- With cb -->

      module.exports = {
         sendEmail: function(user, subject, text, callback) {
            var smtpTransport = nodemailer.createTransport({
              service: 'gmail',
              auth: {
                user: config.email,
                pass: config.gmlpwd
              }
            });
            var mailOptions = {
              to: user,
              from: config.email,
              subject: subject,
              text: text
            };
            smtpTransport.sendMail(mailOptions, function(err) {
              if (err) callback({ err })
              callback({ result: "All is ok" })
            });
        }
      }

      // 

    var mailer = require('./file.js');
    mailer.sendMail('go@mail.com', 'Hello world', 'Lorem ipsum dolor sit ammet', function({ err, result}){
      if (err) {
        console.log(err, '- Some error')

      } else {
        console.log(result, 'Some code here')
      }
    })
  <!-- With Async promise -->

  module.exports = {
     sendEmail:  new Promise(function(resolve, reject){
        function(user, subject, text) {
          var smtpTransport = nodemailer.createTransport({
            service: 'gmail',
            auth: {
              user: config.email,
              pass: config.gmlpwd
            }
          });
          var mailOptions = {
            to: user,
            from: config.email,
            subject: subject,
            text: text
          };
          smtpTransport.sendMail(mailOptions, function(err) {
            if (err) reject({ err })
            resolve({ result: 'All is ok result here'})
          });
      }
    }
  }

  // 

var mailer = require('./file.js');
mailer.sendMail('go@mail.com', 'Hello world', 'Lorem ipsum dolor sit ammet').then(function ({ result}) {
  console.log( 'All is ok')
})
Sporx
  • 29
  • 3
0

I prefer to use async/await in such case, In your case you just need to make your functions along with objects and export it, Let's take a look in the below example.

File1: userController.js

const userUtils = require('./userUtils');

const userCtr = {};

userCtr.searchUser = async (req, res) => {
  try {
    const { userName } = req.query;
    const result = await userUtils.searchUser(userName);
    return res.status(200).json(result);
  } catch (err) {
    return res.status(err.code).json({ error: err.error });
  }
};

module.exports = userCtr;

File2: userUtils.js

const userUtils = {};

userUtils.searchUser = async (userName) => {
  try {
    if (userName) {
      // ...Do some cool stuff
      const result = [];
      return result;
    }
    const errorObj = { code: 400, error: 'ERR_VALID_PARAM' };
    throw errorObj;
  } catch (err) {
    console.error(err);
    throw err;
  }
};

module.exports = userUtils;

In above instance we calling a function searchUser() from userUtils which will return an empty array if arguments are present otherwise it will throw an error. It's just a simple use-case for your understanding of module.exports

Neel Rathod
  • 2,013
  • 12
  • 28