Javascript 和 promise with Q - promise 中的闭包问题



我使用Node.js和Q编写服务器端异步代码。我是promise的新手(一般来说,我是异步编程的新手),我遇到了一些问题,这些问题我无法通过查看Q文档来解决。这是我的代码(它是coffeescript-如果你想看到javascript,请告诉我):

templates = {}
promises = []
for type in ['html', 'text']
    promises.push Q.nfcall(fs.readFile
        , "./email_templates/#{type}.ejs"
        , 'utf8'
        ).then (data)->
            # the problem is right here - by the time
            # this function is called, we are done
            # iterating through the loop, and the value 
            # of type is incorrect
            templates[type] = data
Q.all(promises).then(()->
    console.log 'sending email...'
    # send an e-mail here...
).done ()->
    # etc

希望我的评论能解释这个问题。我想遍历一个类型列表,然后为每个类型运行一个promise链,但问题是type的值在promise的范围之外被更改。我意识到,对于这么短的清单,我可以展开循环,但这不是一个可持续的解决方案。如何确保每个promise都看到不同但本地正确的type值?

您必须将数据分配闭包封装在另一个闭包中,以便在执行内部闭包之前保留类型的值。

有关更多详细信息:http://www.mennovanslooten.nl/blog/post/62

我不知道CoffeeScript,但它应该在JS:中工作

var promises = [];
var templates = {};
var ref = ['html', 'text'];
for (var i = 0, len = ref.length; i < len; i++) {
    var type = ref[i];
    promises.push(Q.nfcall(fs.readFile, "./email_templates/" + type + ".ejs", 'utf8').then((function (type) {
        return function (data) {
            return templates[type] = data;
        };
    }(type))));
}
Q.all(promises).then(function() {
    return console.log('sending email...');
    // ...
}).done(function() {
    // ...
});

编辑:CoffeeScript翻译:

templates = {}
promises = []
for type in ['html', 'text']
    promises.push Q.nfcall(fs.readFile
        , "./email_templates/#{type}.ejs"
        , 'utf8'
        ).then do (type)->
            (data)->
                 templates[type] = data
Q.all(promises).then(()->
    console.log 'sending email...'
).done ()->
    console.log '...'

重要的部分是:

).then do (type)->
    (data)->
        templates[type] = data

最新更新