This is a reupload of an old presentation I’ve made in graduate school. Although it’s a bit dated, I believe the logic (and creativity) behind it still applies.
However, it can also be a PITA, since sometimes, certain events might happen before we have a chance to even listen to them with Event Listeners. Event Listeners are better for things like keypress events and mouse clicks. They can happen many times and don’t relate to events.
Unlike Event Listeners, promises can succeed or fail only once. They can also have respective callbacks added later, despite the fact the promises have already taken place. This means you can chain promises, much like functions or methods. Therefore, promises are great for when you want to focus on whether something actually happened or not, and then react appropriately.
Think of a JS promise like a real promise — someone promises you something, and several things can happen as a result.
- Pending — The promise has yet to be completed.
- Settled — The promise has been completed.
- Resolved — The promise has been kept!
- Rejected — Sorry, looks like the promise has been broken!
Let’s say I wanna go grab some tacos with Andrew. So, I make him a promise.
Yo, Andrew! Let’s go grab some tacos on Friday!
It takes a while for Friday to arrive, right? So in the meantime, I can go do other things! Friday rolls in, it’s time to talk to Andrew about that promise I made earlier…
Scenario A: Yo, Andrew, ready to go get tacos? — “Yes! Tacooos!”
Scenario B: Yeah, uh, I’m still working on those wireframes. Sorry! — “You guys are no fun!”
Let’s say I want to make another promise, this time to Wasim, but it depends on the previous promise. So that means I can’t make the second one until the first one takes place. Simple, right?
Yo, Wasim! Andrew and I went for tacos. Wanna see? — “Uh, sure, dude, whatever…”
In this scenario, there is no way for me to show Wasim pictures of tacos if I haven’t even gone out with Andrew for tacos in the first place, right? The same logic works here.
Wanna make a promise and have it complete only when all of its conditions are met (instead of chaining on and on)? Use Promise.all().
That way, you have one promise that takes an array of promises, and is fulfilled only when all of its sub promises are fulfilled. That way, you grab ’em all at once.
Wanna do the opposite and have a promise fulfill or reject ASAP and go through your chain quickly? Use Promise.race() instead!
Keep in mind, if the first item fails, the entire promise stops. It’ll only race to the finish line if it keeps getting green lights…so to speak.