包含承诺的for循环中的词法范围? [英] Lexical scoping in a for loop enclosing a promise?

查看:20
本文介绍了包含承诺的for循环中的词法范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ids 对象,它将 id 字符串映射到 product 对象.

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. :(

我正在使用一个用于数据库交互的库,它公开了 Promise(由上面的 then 函数表示).我试图在 then 函数中打印出 product 变量,但我似乎只得到了 中的最后一个 idids,所以看起来这是一个范围问题.如何正确确定 product 变量的范围,以便它在每个循环的 then 函数中打印出不同的产品?

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 确实找到了 描述您的问题的正确副本.实际上,您遇到了一个范围界定问题,其中 product 对于循环体来说是非本地的,并且您只能从异步回调中获取最后一项.

@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.

如何正确确定产品变量的范围,以便它在 then 回调中打印出不同的产品?

How can I scope the product variable properly so that it prints out a different product in the then callback?

在惯用的 coffeescript 中,您将使用 do 表示法 表示 IEFE在循环中:

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) ->
    …

这篇关于包含承诺的for循环中的词法范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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