在包含promise的for循环中的词法作用域? [英] Lexical scoping in a for loop enclosing a promise?
问题描述
我有一个 ids
对象,它将 id
字符串映射到 c $ c>对象。
I have an ids
object, which maps id
strings to product
objects.
for id of ids
product = ids[id]
console.log product # Prints out something different each loop. :)
Product.create(product).then ->
console.log product # Only prints out the last id each loop. :(
我使用库进行数据库交互,我试图在中打印出
产品
变量,然后 code>函数,但是我只是在 ids
中找到最后的 id
这是一个范围问题我如何适当地范围产品
变量,以便它打印出一个不同的产品在然后
函数每个循环?
I'm using a library for database interactions, which exposes promises (indicated by the then
function above). I'm trying to print out the product
variable inside the then
function, but I only seem to be getting the last id
in ids
, so it looks like it's a scoping issue. How can I scope the product
variable properly so that it prints out a different product in the then
function each loop?
推荐答案
@false确实找到产品
@false did find the right duplicate describing your issue. Indeed, you've got a scoping issue where product
is non-local to the loop body, and you get the last item only from your asynchronous callbacks.
如何区分产品变量
在惯用coffeescript中,您将使用 do
符号:
In idiomatic coffeescript, you will use the do
notation for the IEFE in the loop:
for id of ids
do (product = ids[id]) ->
console.log product
Product.create(product).then ->
console.log product
或者,直接从 of
-loop:
Or, drawing the property value directly from the of
-loop:
for id, product of ids
do (product) ->
…
这篇关于在包含promise的for循环中的词法作用域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!