title: Is my NodeJS promise code race condition safe?
body: <p>I am currently writing a small multiplayer game in nodejs. </p>
  
  <p>When a player joins I want to load them onto the game world at their requested position. It is possible however that this position is occupied, if so I look around for the nearest available free space and load them at that location.</p>
  
  <p>My way of doing this is as follows:</p>
  
  <pre><code>    function playerJoin(){    
          let playerTank = new Tank();
          this.findEmptyArea(playerTank, 100, 100).then((result) =&gt; {
              if (!result.success) {
                  return;
              }
              addObjectToWorld(playerTank, result.x, result.y);    
          } 
      }
  
  
      function findEmptyArea(object, x, y){   
          return new Promise((resolve, reject) =&gt; {
            // Psuedo code: code iterates over game objects testing for 
            // collisions . if the requested position is free uses that else 
            // finds an empty nearby location and returns it
            return resolve({success: true, x: freeX, y: freeY});
  
            // fails to find empty location for object
            return resolve({ success: false });
          } 
    }
  </code></pre>
  
  <p>This is not the actual code but a stripped down version to make it clearer. My question is this:</p>
  
  <p>When a user connects via the web socket, the function playerJoin runs. it then creates a new player tank , finds the free area and returns a promise, if it was successful the player tank is added to the world at the position.</p>
  
  <p>Having looked closely at this I have wondered whether this code is flawed. Is it possible that addObjectToWorld is called on a location that is not actually free?</p>
  
  <p>Such as the following:</p>
  
  <ol>
  <li>player1 connects playerJoin called for player1 </li>
  <li>findEmptyArea called within playerJoin for player1 </li>
  <li>player 2 connects playerJoin called for player2 </li>
  <li>findEmptyArea called within playerJoin for player2</li>
  <li>findEmptyArea promise for player1 finds a free space at 10,10 and
  returns promise. </li>
  <li><p>findEmptyArea promise for player2 finds a free
  space at 10,10 and returns promise.</p></li>
  <li><p>The .then() Promise code block
  in playerJoin (after findEmptyArea) for player 1 runs, putting the player at 10,10 via
  addObjectToWorld </p></li>
  <li>The .then() Promise code block in playerJoin for
  player 2 runs, putting the player at 10,10 via addObjectToWorld..
  and the game crashes</li>
  </ol>
  
  <p>So I guess my question is, when a promise resolves, will the .then code block run immediately which runs addObjectToWorld runs straight away, or will other code potentially run first (such as another player also finding the area free)</p>
  
  <p>Thank you for your help</p>