Promise Basics

A promise is a placeholder for the result of an asynchronous operation. Instead of subscribing to an event or passing a callback to a function, the function can return a promise, like this:

  1. // readFile promises to complete at some point in the future
  2. let promise = readFile("example.txt");

In this code, readFile() doesn’t actually start reading the file immediately; that will happen later. Instead, the function returns a promise object representing the asynchronous read operation so you can work with it in the future. Exactly when you’ll be able to work with that result depends entirely on how the promise’s lifecycle plays out.

The Promise Lifecycle

Each promise goes through a short lifecycle starting in the pending state, which indicates that the asynchronous operation hasn’t completed yet. A pending promise is considered unsettled. The promise in the last example is in the pending state as soon as the readFile() function returns it. Once the asynchronous operation completes, the promise is considered settled and enters one of two possible states:

  1. Fulfilled: The promise’s asynchronous operation has completed successfully.
  2. Rejected: The promise’s asynchronous operation didn’t complete successfully due to either an error or some other cause.

An internal [[PromiseState]] property is set to "pending", "fulfilled", or "rejected" to reflect the promise’s state. This property isn’t exposed on promise objects, so you can’t determine which state the promise is in programmatically. But you can take a specific action when a promise changes state by using the then() method.

The then() method is present on all promises and takes two arguments. The first argument is a function to call when the promise is fulfilled. Any additional data related to the asynchronous operation is passed to this fulfillment function. The second argument is a function to call when the promise is rejected. Similar to the fulfillment function, the rejection function is passed any additional data related to the rejection.

I> Any object that implements the then() method in this way is called a thenable. All promises are thenables, but not all thenables are promises.

Both arguments to then() are optional, so you can listen for any combination of fulfillment and rejection. For example, consider this set of then() calls:

  1. let promise = readFile("example.txt");
  2. promise.then(function(contents) {
  3. // fulfillment
  4. console.log(contents);
  5. }, function(err) {
  6. // rejection
  7. console.error(err.message);
  8. });
  9. promise.then(function(contents) {
  10. // fulfillment
  11. console.log(contents);
  12. });
  13. promise.then(null, function(err) {
  14. // rejection
  15. console.error(err.message);
  16. });

All three then() calls operate on the same promise. The first call listens for both fulfillment and rejection. The second only listens for fulfillment; errors won’t be reported. The third just listens for rejection and doesn’t report success.

Promises also have a catch() method that behaves the same as then() when only a rejection handler is passed. For example, the following catch() and then() calls are functionally equivalent:

  1. promise.catch(function(err) {
  2. // rejection
  3. console.error(err.message);
  4. });
  5. // is the same as:
  6. promise.then(null, function(err) {
  7. // rejection
  8. console.error(err.message);
  9. });

The intent behind then() and catch() is for you to use them in combination to properly handle the result of asynchronous operations. This system is better than events and callbacks because it makes whether the operation succeeded or failed completely clear. (Events tend not to fire when there’s an error, and in callbacks you must always remember to check the error argument.) Just know that if you don’t attach a rejection handler to a promise, all failures will happen silently. Always attach a rejection handler, even if the handler just logs the failure.

A fulfillment or rejection handler will still be executed even if it is added to the job queue after the promise is already settled. This allows you to add new fulfillment and rejection handlers at any time and guarantee that they will be called. For example:

  1. let promise = readFile("example.txt");
  2. // original fulfillment handler
  3. promise.then(function(contents) {
  4. console.log(contents);
  5. // now add another
  6. promise.then(function(contents) {
  7. console.log(contents);
  8. });
  9. });

In this code, the fulfillment handler adds another fulfillment handler to the same promise. The promise is already fulfilled at this point, so the new fulfillment handler is added to the job queue and called when ready. Rejection handlers work the same way.

I> Each call to then() or catch() creates a new job to be executed when the promise is resolved. But these jobs end up in a separate job queue that is reserved strictly for promises. The precise details of this second job queue aren’t important for understanding how to use promises so long as you understand how job queues work in general.

Creating Unsettled Promises

New promises are created using the Promise constructor. This constructor accepts a single argument: a function called the executor, which contains the code to initialize the promise. The executor is passed two functions named resolve() and reject() as arguments. The resolve() function is called when the executor has finished successfully to signal that the promise is ready to be resolved, while the reject() function indicates that the executor has failed.

Here’s an example that uses a promise in Node.js to implement the readFile() function from earlier in this chapter:

  1. // Node.js example
  2. let fs = require("fs");
  3. function readFile(filename) {
  4. return new Promise(function(resolve, reject) {
  5. // trigger the asynchronous operation
  6. fs.readFile(filename, { encoding: "utf8" }, function(err, contents) {
  7. // check for errors
  8. if (err) {
  9. reject(err);
  10. return;
  11. }
  12. // the read succeeded
  13. resolve(contents);
  14. });
  15. });
  16. }
  17. let promise = readFile("example.txt");
  18. // listen for both fulfillment and rejection
  19. promise.then(function(contents) {
  20. // fulfillment
  21. console.log(contents);
  22. }, function(err) {
  23. // rejection
  24. console.error(err.message);
  25. });

In this example, the native Node.js fs.readFile() asynchronous call is wrapped in a promise. The executor either passes the error object to the reject() function or passes the file contents to the resolve() function.

Keep in mind that the executor runs immediately when readFile() is called. When either resolve() or reject() is called inside the executor, a job is added to the job queue to resolve the promise. This is called job scheduling, and if you’ve ever used the setTimeout() or setInterval() functions, then you’re already familiar with it. In job scheduling, you add a new job to the job queue to say, “Don’t execute this right now, but execute it later.” For instance, the setTimeout() function lets you specify a delay before a job is added to the queue:

  1. // add this function to the job queue after 500ms have passed
  2. setTimeout(function() {
  3. console.log("Timeout");
  4. }, 500);
  5. console.log("Hi!");

This code schedules a job to be added to the job queue after 500ms. The two console.log() calls produce the following output:

  1. Hi!
  2. Timeout

Thanks to the 500ms delay, the output that the function passed to setTimeout() was shown after the output from the console.log("Hi!") call.

Promises work similarly. The promise executor executes immediately, before anything that appears after it in the source code. For instance:

  1. let promise = new Promise(function(resolve, reject) {
  2. console.log("Promise");
  3. resolve();
  4. });
  5. console.log("Hi!");

The output for this code is:

  1. Promise
  2. Hi!

Calling resolve() triggers an asynchronous operation. Functions passed to then() and catch() are executed asynchronously, as these are also added to the job queue. Here’s an example:

  1. let promise = new Promise(function(resolve, reject) {
  2. console.log("Promise");
  3. resolve();
  4. });
  5. promise.then(function() {
  6. console.log("Resolved.");
  7. });
  8. console.log("Hi!");

The output for this example is:

  1. Promise
  2. Hi!
  3. Resolved

Note that even though the call to then() appears before the console.log("Hi!") line, it doesn’t actually execute until later (unlike the executor). That’s because fulfillment and rejection handlers are always added to the end of the job queue after the executor has completed.

Creating Settled Promises

The Promise constructor is the best way to create unsettled promises due to the dynamic nature of what the promise executor does. But if you want a promise to represent just a single known value, then it doesn’t make sense to schedule a job that simply passes a value to the resolve() function. Instead, there are two methods that create settled promises given a specific value.

Using Promise.resolve()

The Promise.resolve() method accepts a single argument and returns a promise in the fulfilled state. That means no job scheduling occurs, and you need to add one or more fulfillment handlers to the promise to retrieve the value. For example:

  1. let promise = Promise.resolve(42);
  2. promise.then(function(value) {
  3. console.log(value); // 42
  4. });

This code creates a fulfilled promise so the fulfillment handler receives 42 as value. If a rejection handler were added to this promise, the rejection handler would never be called because the promise will never be in the rejected state.

Using Promise.reject()

You can also create rejected promises by using the Promise.reject() method. This works like Promise.resolve() except the created promise is in the rejected state, as follows:

  1. let promise = Promise.reject(42);
  2. promise.catch(function(value) {
  3. console.log(value); // 42
  4. });

Any additional rejection handlers added to this promise would be called, but not fulfillment handlers.

I> If you pass a promise to either the Promise.resolve() or Promise.reject() methods, the promise is returned without modification.

Non-Promise Thenables

Both Promise.resolve() and Promise.reject() also accept non-promise thenables as arguments. When passed a non-promise thenable, these methods create a new promise that is called after the then() function.

A non-promise thenable is created when an object has a then() method that accepts a resolve and a reject argument, like this:

  1. let thenable = {
  2. then: function(resolve, reject) {
  3. resolve(42);
  4. }
  5. };

The thenable object in this example has no characteristics associated with a promise other than the then() method. You can call Promise.resolve() to convert thenable into a fulfilled promise:

  1. let thenable = {
  2. then: function(resolve, reject) {
  3. resolve(42);
  4. }
  5. };
  6. let p1 = Promise.resolve(thenable);
  7. p1.then(function(value) {
  8. console.log(value); // 42
  9. });

In this example, Promise.resolve() calls thenable.then() so that a promise state can be determined. The promise state for thenable is fulfilled because resolve(42) is called inside the then() method. A new promise called p1 is created in the fulfilled state with the value passed from thenable (that is, 42), and the fulfillment handler for p1 receives 42 as the value.

The same process can be used with Promise.resolve() to create a rejected promise from a thenable:

  1. let thenable = {
  2. then: function(resolve, reject) {
  3. reject(42);
  4. }
  5. };
  6. let p1 = Promise.resolve(thenable);
  7. p1.catch(function(value) {
  8. console.log(value); // 42
  9. });

This example is similar to the last except that thenable is rejected. When thenable.then() executes, a new promise is created in the rejected state with a value of 42. That value is then passed to the rejection handler for p1.

Promise.resolve() and Promise.reject() work like this to allow you to easily work with non-promise thenables. A lot of libraries used thenables prior to promises being introduced in ECMAScript 6, so the ability to convert thenables into formal promises is important for backwards-compatibility with previously existing libraries. When you’re unsure if an object is a promise, passing the object through Promise.resolve() or Promise.reject() (depending on your anticipated result) is the best way to find out because promises just pass through unchanged.

Executor Errors

If an error is thrown inside an executor, then the promise’s rejection handler is called. For example:

  1. let promise = new Promise(function(resolve, reject) {
  2. throw new Error("Explosion!");
  3. });
  4. promise.catch(function(error) {
  5. console.log(error.message); // "Explosion!"
  6. });

In this code, the executor intentionally throws an error. There is an implicit try-catch inside every executor such that the error is caught and then passed to the rejection handler. The previous example is equivalent to:

  1. let promise = new Promise(function(resolve, reject) {
  2. try {
  3. throw new Error("Explosion!");
  4. } catch (ex) {
  5. reject(ex);
  6. }
  7. });
  8. promise.catch(function(error) {
  9. console.log(error.message); // "Explosion!"
  10. });

The executor handles catching any thrown errors to simplify this common use case, but an error thrown in the executor is only reported when a rejection handler is present. Otherwise, the error is suppressed. This became a problem for developers early on in the use of promises, and JavaScript environments address it by providing hooks for catching rejected promises.