如何在 javascript 中使模块异步

how to make module asynchronous in javascript

我是 javascript 的新人。我有一个使用 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);
});

现在我想以异步方式调用这个模块。我应该实现 promise 还是使用 async, await?

根据 sendgrid 的 docs,promises 已经实现,这使得这更容易一些,因为您可以 return 来自您的模块的 promise。例如,如果您只想使用该承诺,您可以:

//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)
}

现在您可以像这样简单地使用它:

mail = require('./mymodule')

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