【问题标题】:how to make module asynchronous in javascript如何在javascript中使模块异步
【发布时间】:2023-03-09 02:17:01
【问题描述】:

我是 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?

【问题讨论】:

  • 顺便说一句,您发布了您的 API 密钥,我会尽快使其失效。
  • 删除它没有帮助。它仍然可见
  • setTimeout() 应该可以工作。
  • 还有一个提示(如果您在浏览器上使用 Javascript):w3schools.com/html/html5_webworkers.asp
  • 是的,你应该实现一个promise 并且然后使用async/await语法来使用它。

标签: javascript asynchronous ecmascript-6 sendgrid ecmascript-2017


【解决方案1】:

根据 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
})

【讨论】:

    猜你喜欢
    • 2018-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-21
    • 2017-03-24
    • 1970-01-01
    • 2014-03-12
    相关资源
    最近更新 更多