Data Races in JavaScript?

后端 未结 4 1588
一个人的身影
一个人的身影 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 07:04

    Node uses an event loop. You can think of this as a queue. So we can assume, that your for loop puts the function() { score++; } callback arbitrary_length times on this queue. After that the js engine runs these one by one and increase score each time. So yes. The only exception if a callback is not called or the score variable is accessed from somewhere else.

    Actually you can use this pattern to do tasks parallel, collect the results and call a single callback when every task is done.

    var results = [];
    for (var i = 0; i < arbitrary_length; i++) {
         async_task(i, function(result) {
              results.push(result);
              if (results.length == arbitrary_length)
                   tasksDone(results);
         });
    }
    

提交回复
热议问题