Quick explanation of JavaScript Promises

"JavaScript Promises: reason about async events, serially chain them, reduce them. General replacement for XHR"

What is a promise? Conceptually and outside the context of code, a promise is either a willful intention of achieving a result or a promise is considered the actual result itself. EcmaScript 6 (ES6) introduces the Promises API which is currently implemented by most browsers (and Edge but not IE according to caniuse.com - but there's a polyfill for that). So a JavaScript Promise is simply an object of some callback functions to call when the "promise" reaches some conclusion, either resolving successfully or rejecting due to some error. Thus a promise has 3 states (internal states, mind you), starting as unfulfilled or pending, then being fulfilled (thus calling the resolve() callback) if not failed or rejected (thus calling the 2nd parameter, the reject() callback). A promise returns something immediately but doesn't promise to be any particular value, and its return can't be used as a value in place of the promised value. A Promise helps you reason about what to do with the resolved result (and providing a chainable then method to make your code read sequential while still having a way for errors to bubble up and be handled).

Note: jQuery also has something called Promises but they aren't quite the same. Wrap a jQuery promise with ES6 Promises with Promise.resolve.

Note: While CasperJS/PhantomJS code also uses .then().then() chains, they are not Promises, although they do help deal with the async nature of makeing http requests. Promise chains .then().then() because each then() itself returns a Promise while making some async request.

Note: WinJS, the Windows Library for JavaScript, has it's own WinJS.Promise.

Promise is a class. You use it to create a Promise object by instantiating it with your "resolver" code (what you want to execute in order to make this promise come true). Then you use it with then(fn) to write the code for what you'd do next in the normal (fulfilling) scenario. And if that scenario requires another asynchronous action to occur then return another Promise and chain your next sequence of statements in the next then(). And so on.

Add new comment