how to make module asynchronous in javascript -


i new in javascript. have simple module 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 sendgrid fun'; var content = new helper.content('text/plain', 'and easy anywhere, 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 want call module in asynchronous way. should implement promise or use async, await?

according sendgrid's docs, promises implemented, makes little easier since can return promise module. example if want use promise 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 sendgrid fun'; var content = new helper.content('text/plain', 'and easy anywhere, 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 can use like:

mail = require('./mymodule')  mail("from@example.com", "subject", "to@example.com", content) .then(function(response) {     // use response.body etc }) 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -