Javascript和承诺与Q – 封闭的承诺问题

我使用Node.js和Q编写服务器端的asynchronous代码。 我对诺言是新的(对于asynchronous编程我一般都是新手),而且我遇到了一些麻烦,我不能通过查看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 

希望我的意见解释了这个问题。 我想遍历一个types列表,然后为每个types运行一个promise的链,但是问题是type的值在promise的范围之外被改变了。 我意识到,对于这样一个简短的清单,我可以展开循环,但这不是一个可持续的解决scheme。 我怎样才能确保每个承诺看到一个不同的,但本地正确的价值type

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

欲了解更多详情: 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