JS Promise cheatsheet
This document contains various examples on how promises behave in different situations. It is created and maintained by Maurycy Zarzycki, Retrocade.net, its source is available on Github. All suggestions and issues can be communicated via Github's Issues page.
Recommended reading: Promises/A+.
Table of Contents
Promise vocabulary
This section refers specifically to the vocabulary used in this document to make finding specific examples easier, though the code samples themselves should be self explanatory.
-
Promise - An object which represents the eventual result of an asynchronous
operation.
new Promise()
,Promise.resolve()
,Promise.reject()
all return a promise object; -
Executor - A function passed to Promise constructor, ie.
new Promise(<executor>)
and takes two callback arguments, one for resolving the promise and one for rejecting it:function executor(resolve, reject)
; -
Then() - A method of a promise object which takes two optional callback
arguments, one for handling the case when the promise is resolved (fulfilled) and another for
when it is rejected, ie:
.then(onResolved, onRejected)
. It returns a new promise which is pending until Then is handled. - onResolved - One of the two possible promise handlers, defined in Then(), is called when the promise to which it is attached is resolved. This can happen by: explicitly resolving promise, returning from onResolved or onRejected any value other than a rejected promise, not returning anything from either of those handlers.
- onRejected - One of the two possible promise handlers, defined in Then(), is called when the promise to which it is attached is rejected. This can happen by: explicitly rejecting promise, returning from onResolved or onRejected a rejected promise, throwing an error inside a promise handler.
Basic promise behaviors
Promise executor is called immediately upon promise creation
Then() resolution is asynchronous
Then() by default resolve the returned promise, with the single exception of returning a rejected promise
Rejected promise skips all onResolved handlers
Throwing an error rejects a promise
Returnin nothing inside catch stops the rejection
Nested promises are handled first
Passing non-function to then ignores that 'then'
Complex promise behaviors
Calling then() twice on the same promise is valid and creates two separate promise branches
Errors thrown inside the executor automatically reject the promise
Returning a resolved promise in executor does not resolve the promise
Resolving the promise multiple times ignores the subsequent calls
Doing Promise.resolve() on another promise passes it on