Javascript& Q的诺言-诺言中的关闭问题 [英] Javascript & promises with Q - closure problems in promises

查看:84
本文介绍了Javascript& Q的诺言-诺言中的关闭问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Node.js和Q编写服务器端异步代码。我对诺言不熟悉(而且一般来说,我对异步编程也很陌生),但是我遇到了一些麻烦,无法通过盯着Q文档来解决。这是我的代码(是咖啡脚本-让我知道您是否想查看JavaScript):

I'm using Node.js and Q to write server-side asynchronous code. I'm new to promises (and I'm new to asynchronous programming in general), and I'm having a bit of trouble that I haven't been able to solve by staring at the Q documentation. Here's my code (it's coffeescript - let me know if you want to see the javascript instead):

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

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

Hopefully my comments explained the problem. I want to iterate through a list of types, and then run a chain of promises for each type, but the problem is that the value of type is being changed outside of the scope of the promises. I realize that, for such a short list, I can just unroll the loop, but this is not a sustainable solution. How can I ensure that each promise sees a different yet locally correct value of type?

推荐答案

您必须将数据赋值闭包封装在另一个闭包中,以便保留类型的值,直到执行内部闭包为止。

You have to encapsulate your data assignment closure in another closure, so that the value of type is preserved until the inner closure is executed.

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

这篇关于Javascript& Q的诺言-诺言中的关闭问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆