Implementing JavaScript promises in a networked application

In our last section, we saw how to take input from the player of our game and send that through Redux to update the application state, and then refresh the user interface. But as we learned on day one, when we submit a call to the Ethereum network we don't get an immediate response, and there's a delay. Unfortunately, we can't proceed until we have that response, so what do we do?

Before we answer that question, let me show you what the underlying problem is. It stems from the way JavaScript works. Let's take a look at this code:

console.log('1')
setTimeout(() => {console.log('2')}, 3000)
console.log('3')
setTimeout(() => {console.log('4')}, 1000)

In the preceding code, we have four lines, each printing out the numbers 1 to 4. Well, what happens when we run this? If you predicted that it prints out 1,3,4,2, you'd be right, because what happens is JavaScript executes the first line, it prints out the number 1, then it executes the second line. This line is where the problem starts as it executes the setTimeout() function, but doesn't know that we want it to wait until the timer completes. So it calls the setTimeout() function, and it moves on to the next line where it prints out 3, then on to the final line where there's another timer. One second later, it prints out the number four, and two seconds after that it finally prints out the number 2, when the 3,000 millisecond delay that was specified expires. 

Now, imagine if instead of writing a number out to the console log, we were actually waiting for data to return from our Solidity contract, so we can use it in our application, wouldn't that cause problems, because we would be trying to use data before it actually existed? So, how do we use JavaScript promises to solve this problem?