Text of web.dev › articles › promises as Styx crawled it on Nov 19, 2026. The page may have changed since. Only its words are kept, without pictures or layout, and only the first part of a long page.

Open the live page

JavaScript promises: An introduction | Articles | web.dev

Skip to main content English Deutsch Español Español – América Latina Français Indonesia Italiano Polski Português – Brasil Tiếng Việt Türkçe Русский עברית العربيّة فارسی हिंदी বাংলা ภาษาไทย 中文 – 简体 中文 – 繁體 日本語 한국어 Sign in Articles Modern Web Guidance is now stable! Upgrade your coding agents with expert-vetted web development best practices.

Read the announcement . Home Articles JavaScript promises: An introduction Stay organized with collections Save and categorize content based on your preferences. Promises simplify deferred and asynchronous computations. A promise represents an operation that hasn't completed yet. Jake Archibald Developers, prepare yourself for a pivotal moment in the history of web development. [Drumroll begins] Promises have arrived in JavaScript! [Fireworks explode, glittery paper rains from above, the crowd goes wild] At this point you fall into one of these categories: People are cheering around you, but you're not sure what all the fuss is about.

Maybe you're not even sure what a "promise" is. You'd shrug, but the weight of glittery paper is weighing down on your shoulders. If so, don't worry about it, it took me ages to work out why I should care about this stuff. You probably want to begin at the beginning . You punch the air! About time right? You've used these Promise things before but it bothers you that all implementations have a slightly different API. What's the API for the official JavaScript version?

You probably want to begin with the terminology . You knew about this already and you scoff at those who are jumping up and down like it's news to them. Take a moment to bask in your own superiority, then head straight to the API reference . Browser support and polyfill Browser Support 32 12 29 8 Source To bring browsers that lack a complete promises implementation up to spec compliance, or add promises to other browsers and Node.js, check out the polyfill (2k gzipped).

What's all the fuss about? JavaScript is single threaded, meaning that two bits of script cannot run at the same time; they have to run one after another. In browsers, JavaScript shares a thread with a load of other stuff that differs from browser to browser. But typically JavaScript is in the same queue as painting, updating styles, and handling user actions (such as highlighting text and interacting with form controls).

Activity in one of these things delays the others. As a human being, you're multithreaded. You can type with multiple fingers, you can drive and hold a conversation at the same time. The only blocking function we have to deal with is sneezing, where all current activity must be suspended for the duration of the sneeze. That's pretty annoying, especially when you're driving and trying to hold a conversation. You don't want to write code that's sneezy.

You've probably used events and callbacks to get around this. Here are events: var img1 = document . querySelector ( '.img-1' ); img1 . addEventListener ( 'load' , function () { // woo yey image loaded }); img1 . addEventListener ( 'error' , function () { // argh everything's broken }); This isn't sneezy at all. We get the image, add a couple of listeners, then JavaScript can stop executing until one of those listeners is called.

Unfortunately, in the example above, it's possible that the events happened before we started listening for them, so we need to work around that using the "complete" property of images: var img1 = document . querySelector ( '.img-1' ); function loaded () { // woo yey image loaded } if ( img1 . complete ) { loaded (); } else { img1 . addEventListener ( 'load' , loaded ); } img1 . addEventListener ( 'error' , function () { // argh everything's broken }); This doesn't catch images that errored before we got a chance to listen for them; unfortunately the DOM doesn't give us a way to do that.

Also, this is loading one image. Things get even more complex if we want to know when a set of images have loaded. Events aren't always the best way Events are great for things that can happen multiple times on the same object— keyup , touchstart etc. With those events you don't really care about what happened before you attached the listener. But when it comes to async success/failure, ideally you want something like this: img1 . callThisIfLoadedOrWhenLoaded ( function () { // loaded }). orIfFailedCallThis ( function () { // failed }); // and… whenAllTheseHaveLoaded ([ img1 , img2 ]). callThis ( function () { // all loaded }). orIfSomeFailedCallThis ( function () { // one or more failed }); This is what promises do, but with better naming.

If HTML image elements had a "ready" method that returned a promise, we could do this: img1 . ready () . then ( function () { // loaded }, function () { // failed }); // and… Promise . all ([ img1 . ready (), img2 . ready ()]) . then ( function () { // all loaded }, function () { // one or more failed }); At their most basic, promises are a bit like event listeners except: A promise can only succeed or fail once. It cannot succeed or fail twice, neither can it switch from success to failure or vice versa.

If a promise has succeeded or failed and you later add a success/failure callback, the correct callback will be called, even though the event took place earlier. This is extremely useful for async success/failure, because you're less interested in the exact time something became available, and more interested in reacting to the outcome. Promise terminology Domenic Denicola proof read the first draft of this article and graded me "F" for terminology.

He put me in detention, forced me to copy out States and Fates 100 times, and wrote a worried letter to my parents. Despite that, I still get a lot of the terminology mixed up, but here are the basics: A promise can be: fulfilled - The action relating to the promise succeeded rejected - The action relating to the promise failed pending - Hasn't fulfilled or rejected yet settled - Has fulfilled or rejected The spec also uses the term thenable to describe an object that is promise-like, in that it has a then method.

This term reminds me of ex-England Football Manager Terry Venables so I'll be using it as little as possible. Promises arrive in JavaScript! Promises have been around for a while in the form of libraries, such as: Q when WinJS RSVP.js The above and JavaScript promises share a common, standardized behaviour called Promises/A+ . If you're a jQuery user, they have something similar called Deferreds . However, Deferreds aren't Promise/A+ compliant, which makes them subtly different and less useful , so beware. jQuery also has a Promise type , but this is just a subset of Deferred and has the same issues.

Although promise implementations follow a standardized behaviour, their overall APIs differ. JavaScript promises are similar in API to RSVP.js. Here's how you create a promise: var promise = new Promise ( function ( resolve , reject ) { // do a thing, possibly async, then… if ( /* everything turned out fine */ ) { resolve ( "Stuff worked!" ); } else { reject ( Error ( "It broke" )); } }); The promise constructor takes one argument, a callback with two parameters, resolve and reject.

Do something within the callback, perhaps async, then call resolve if everything worked, otherwise call reject. Like throw in plain old JavaScript, it's customary, but not required, to reject with an Error object. The benefit of Error objects is they capture a stack trace, making debugging tools more helpful. Here's how you use that promise: promise . then ( function ( result ) { console . log ( result ); // "Stuff worked!" }, function ( err ) { console . log ( err ); // Error: "It broke" }); then() takes two arguments, a callback for a success case, and another for the failure case.

Both are optional, so you can add a callback for the success or failure case only. JavaScript promises started out

The rest of this page is on the live site.