Lexical scoping in a for loop enclosing a promise?

前端 未结 2 1318
情书的邮戳
情书的邮戳 2021-01-28 05:17

I have an ids object, which maps id strings to product objects.

for id of ids
  product = ids[id]
  console.log product #          


        
2条回答
  •  佛祖请我去吃肉
    2021-01-28 05:29

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

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

    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
    

    Or, drawing the property value directly from the of-loop:

    for id, product of ids
      do (product) ->
        …
    

提交回复
热议问题