Asynchronous Programming 101 - 401-advanced-javascript-aimurphy/seattle-javascript-401n13 GitHub Wiki
First, chew on this:
The part of the computer that is carrying out (or "processing") the programs we write is called the processor. The speed at which they can be executed depends on the speed of the processor.
In Synchronous Programming
...functions can only run one at a time and must resolve before the next can fire off. This stops your program for the duration of the wait for the action to complete. So if you have two actions happening they can only happen as quickly as the sum of the two... UNLESS! We run another thread. A thread is another running program, on a different processor. So now we only have to wait as the longest execution time, but we are also now tying up two processors AND the two have to resynchronize results once thy've finished.
In Asynchronous Programming
...we can have multiple action running on the same processor at the SAME TIME. So if we call a function, we don't have to wait for it to finish to work down the queue, the next can fire off immediately afterward and run alongside. Although this style makes sense for programs that don't fit the straight-line, synchronous model, it makes it super awkward for those that do.
So one way to approach async is to make slow moving functions take a callback function as an extra parameter. This way, when that slow function is finished the call back runs with the result. But functions doing asynch work usually return before the work is done, since the callback is going to take care of that. SO... we need another callback to handle that to notify when the response we've been waiting for is available. callback-ception. Oh jeez. So... Promises?
Promises, Promises...
This blew my mind: they are OBJECTS! According to a book I read, promises are objects that represent actions that might happen in the future. Sounds like people promises. So now instead of arranging for another asynch function we return this object that represents the future event. --Think about the cheeseburger example: I pay for the cheeseburger, I get my receipt number but I still have to wait for them to make it and give it to me. It's "promised" to me.
Like people promises, they can also be broken :( Meet resolve and reject. Promise success? Promise resolved! Promise fail? Promise rejected. More on this to come....