我是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,等待?
发布于 2017-08-19 00:44:15
根据sendgrid的docs的说法,promise已经实现了,这使得这一点变得更容易,因为您只需从模块返回该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
})
https://stackoverflow.com/questions/45758825
复制相似问题