0

I am new in javascript. I have simple module which sent email using sendgrid :

    // using SendGrid's v3 Node.js Library
// https://github.com/sendgrid/sendgrid-nodejs
var helper = require('sendgrid').mail;
var fromEmail = new helper.Email('test@test.com');
var toEmail = new helper.Email('sample@sample.com');
var subject = 'Sending with SendGrid is Fun';
var content = new helper.Content('text/plain', 'and easy to do anywhere, even with Node.js');


var mail = new helper.Mail(fromEmail, subject, toEmail, content);

var sg = require('sendgrid')("**********************");
var request = sg.emptyRequest({
  method: 'POST',
  path: '/v3/mail/send',
  body: mail.toJSON()
});

sg.API(request, function (error, response) {
  if (error) {
    console.log('Error response received');
  }
  console.log(response.statusCode);
  console.log(response.body);
  console.log(response.headers);
});

now I want to call this module in an asynchronous way. should I implement promise or use async, await?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
amir
  • 2,443
  • 3
  • 22
  • 49

1 Answers1

1

According to sendgrid's docs, promises are already implemented, which makes this a little easier since you can just return that promise from your module. For example if you just want to use that promise you can:

//mymodule.js

var helper = require('sendgrid').mail;
var fromEmail = new helper.Email('test@test.com');
var toEmail = new helper.Email('sample@sample.com');
var subject = 'Sending with SendGrid is Fun';
var content = new helper.Content('text/plain', 'and easy to do anywhere, even with Node.js');



module.exports = function(from, subject, to, content){
    var mail = new helper.Mail(fromEmail, subject, toEmail, content);

    var sg = require('sendgrid')("**********************");
    var request = sg.emptyRequest({
    method: 'POST',
    path: '/v3/mail/send',
    body: mail.toJSON()
    });

    return sg.API(request)
}

Now you can simply use it like:

mail = require('./mymodule')

mail("from@example.com", "subject", "to@example.com", content)
.then(function(response) {
    // use response.body etc
})
Mark
  • 90,562
  • 7
  • 108
  • 148