0

javascriptが新しいです。今私は、非同期の方法で、このモジュールを呼び出したい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); 
}); 

:私はsendgrid使用して電子メールを送信し、簡単なモジュールを持っています。私は約束を実装するか、非同期を使用する必要がありますか?

+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 
}) 
関連する問題