【发布时间】:2013-12-16 04:24:02
【问题描述】:
我正在使用 Node.js 和 Q 编写服务器端异步代码。我是 Promise 的新手(而且我通常是异步编程的新手),而且我遇到了一些问题,我无法通过盯着 Q 文档来解决。这是我的代码(它是咖啡脚本 - 如果您想查看 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
希望我的 cmets 解释了这个问题。我想遍历类型列表,然后为每种类型运行一系列承诺,但问题是 type 的值正在被更改超出承诺范围。我意识到,对于这么短的列表,我可以展开循环,但这不是一个可持续的解决方案。如何确保每个 Promise 看到不同但本地正确的 type 值?
【问题讨论】:
标签: javascript node.js coffeescript promise q