Skip to content

Instantly share code, notes, and snippets.

@lukechinworth
lukechinworth / jquery-deferreds-promises.md
Last active February 13, 2018 13:22
jQuery Deferreds and Promises

Two ideas: Deferreds and Promises.

Part 1: Deferred

A Deferred object is initially pending. It can be either resolved or rejected. You can do so by literally calling .resolve or .reject on the Deferred object. You can check its state (pending, resolved, or rejected) by calling .state on it. Once it leaves pending (to be either resolved or rejected) it is permanently that state and cannot be undone (unless of course with a page refresh).

These states are nice because you can put code in functions that will only run when the Deferred object has been set to one of these states. This is done with the .done and .fail methods on the Deferred object. Two examples: the first to explain states, and the second to explain running code based on states.

Example 1: