Data Races in JavaScript?

后端 未结 4 1557
一个人的身影
一个人的身影 2021-01-15 06:26

Lets assume I run this piece of code.

var score = 0;
for (var i = 0; i < arbitrary_length; i++) {
     async_task(i, function() { score++; }); // incremen         


        
4条回答
  •  生来不讨喜
    2021-01-15 06:41

    I do think it’s worth noting for others that view this, you have a common mistake in your code. For the variable i you either need to use let or reassign to another variable before passing it into the async_task(). The current implementation will result in each function getting the last value of i.

提交回复
热议问题