且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

包含承诺的for循环中的词法范围?

更新时间:2022-06-24 02:53:35

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