Last week we looked at callbacks and promises. I made a case for using promises to easily coordinate asynchronous code. This week, we’ll dig further into understanding promises and look at the syntax.
Imagine you have a box. You don’t know if there’s anything in the box yet, but you can carry it around and say things about it, like:
“This box is meant to have a gift inside.”
“If the gift is in the box, I should tell everyone the gift is here.”
“If the gift is in the box, I should also write a thank you note.”
“If there’s a letter in the box saying the gift was out of stock, I should go order a different gift.”
You don’t need to know if there’s a gift inside, or a letter, or if the box is empty to say any of those things. Now imagine a gift arrives and is placed in the box. You can then tell everyone that the gift is in the box and write a thank you note. You also still have the box, so you can continue to say things like:
“If the gift is in the box, I should do a dance.”