gpt4 book ai didi

Javascript & promises with Q - promises 中的闭包问题

转载 作者:行者123 更新时间:2023-11-30 10:24:11 25 4
gpt4 key购买 nike

我正在使用 Node.js 和 Q 编写服务器端异步代码。我是 promises 的新手(一般来说我是异步编程的新手),我遇到了一些我无法通过盯着 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

关于Javascript & promises with Q - promises 中的闭包问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20294791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com