Skip to content

Instantly share code, notes, and snippets.

@rrgayhart
Last active March 20, 2017 15:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rrgayhart/11596a68977d154d4735538b5e985edc to your computer and use it in GitHub Desktop.
Save rrgayhart/11596a68977d154d4735538b5e985edc to your computer and use it in GitHub Desktop.
Promises Questions

1. What are the states of a promise?

  • pending - The initial state of a promise.
  • fulfilled - The state of a promise representing a successful operation.
  • rejected - The state of a promise representing a failed operation.

2. What is the difference between a callback, a promise or a generator?

Callback - Callbacks are the fundamental unit of asynchrony in JS. But they're not enough for the evolving landscape of async programming as JS matures.

Promise - next step in the evolution of being able to control async code. Allow you to chain behavior, based on the status of something that is taking a long time to run.

Generator - Inside the generator function body, you use the new yield keyword to pause the function from inside itself. Nothing can pause a generator from the outside; it pauses itself when it comes across a yield. - From es6 generators

3. Why do we have Promises when we already have Callbacks?

First, our brains plan things out in sequential, blocking, single-threaded semantic ways, but callbacks express asynchronous flow in a rather nonlinear, nonsequential way, which makes reasoning properly about such code much harder. Bad to reason about code is bad code that leads to bad bugs.

We need a way to express asynchrony in a more synchronous, sequential, blocking manner, just like our brains do.

Second, and more importantly, callbacks suffer from inversion of control in that they implicitly give control over to another party (often a third-party utility not in your control!) to invoke the continuation of your program. This control transfer leads us to a troubling list of trust issues, such as whether the callback is called more times than we expect.

4. Is it critical that we write Promises all the time?

Naw. It is critical that we understand how to work with them, though, because they're all over the place

5. Is jQuery using promises?

Actually, no - check out promisejs.org for a quick, sort of salty explanation. jQuery predates the promise library. But it has a similar implementation, which is confusing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment