Bluebird - promisification - promisify所有'email-templates'节点模块 - 发送邮件

时间:2015-05-04 03:36:22

标签: node.js promise bluebird node-modules email-templates

我正在尝试将email-templates节点模块转换为promise。我正在使用 bluebird 进行投放,但无法转换。

var emailTemplates = Promise.promisifyAll(require('email-templates'));

promisification节点模块是否支持此转换,或者我是否有任何错误?

已编辑:

我现在这样做,但想把它转换成蓝鸟的承诺。

var emailTemplates = require('email-templates');
var path = require('path');
var templatesDir = path.resolve(__dirname, '../..', 'assets/templates');
var postmark = require('postmark');

var postmarkKey = MY_POSTMARK_KEY;
var postmarkClient = postmark(postmarkKey);

module.exports = {
  sendEmail : function (templateName, locals, callback) {    
            emailTemplates(templatesDir, function (err, template) {
                if (err)
                    return callback(err, null);
                else {
                    template(templateName, locals, function (err, html, text) {
                        if (err) {                        
                            return callback(err, null);
                        }    
                        else {
                            postmarkClient.send({
                                From: locals.from,
                                To: locals.to,
                                Subject: locals.subject,
                                HtmlBody: html
                                TextBody: text
                            }, function (err, responseStatus) {
                                if (err) {                                
                                    return callback(err, null);
                                }
                                else {
                                    return callback(err, responseStatus);
                                }
                            });
                        }
                    });
                }
            });
        }
}

2 个答案:

答案 0 :(得分:1)

emailTemplates是一个函数,所以你可以这样做:

var emailTemplates = Promise.promisify(require('email-templates'));

问题是它表现不好,因为函数本身有一个回调参数,所以你必须这样做:

emailTemplates().then(function(template){
    Promise.fromNode(template.bind(null, "template-name")).then(...
});

答案 1 :(得分:0)

对我来说也是不可思议的,所以我做了手动宣传。

var postmark    = require("postmark");
var client      = new postmark.Client("POSTMARK_API_TEST");
var Promise     = require('bluebird');

exports.sendInviteEmail = function(email) {
    let promise = new Promise((resolve, reject) => {
        client.sendEmail({
            "From": "donotreply@example.com", 
            "To": "target@example.us", 
            "Subject": "Test", 
            "TextBody": "Test Message"
        }, function(error, result) {
            if(error) {
                reject(error);
            } else {
                resolve(result);
            }
        })
    });
    return promise;
}