0

我是JavaScript新手。我有使用sendgrid發送電子郵件的簡單模塊:如何在javascript中使模塊異步

// using SendGrid's v3 Node.js Library 
// https://github.com/sendgrid/sendgrid-nodejs 
var helper = require('sendgrid').mail; 
var fromEmail = new helper.Email('[email protected]'); 
var toEmail = new helper.Email('[email protected]'); 
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); 
}); 

現在我想以異步方式調用此模塊。我應該實現承諾還是使用異步,等待?

+4

順便說一句,你發佈你的API密鑰,我會盡快無效。 – usandfriends

+1

刪除它並沒有幫助。它仍然可見 – baao

+0

setTimeout()應該工作。 – TGarrett

回答

1

根據sendgrid的docs,承諾已經實現,這使得這更容易一些,因爲你可以從模塊中返回承諾。例如,如果你只是想用這個承諾,您可以:

//mymodule.js 

var helper = require('sendgrid').mail; 
var fromEmail = new helper.Email('[email protected]'); 
var toEmail = new helper.Email('[email protected]'); 
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("[email protected]", "subject", "[email protected]", content) 
.then(function(response) { 
    // use response.body etc 
})