Promise

The Promise class is something that exists in many modern JavaScript engines and can be easily polyfilled. The main motivation for promises is to bring synchronous style error handling to Async / Callback style code.

Callback style code

In order to fully appreciate promises let’s present a simple sample that proves the difficulty of creating reliable Async code with just callbacks. Consider the simple case of authoring an async version of loading JSON from a file. A synchronous version of this can be quite simple:

  1. import fs = require('fs');
  2. function loadJSONSync(filename: string) {
  3. return JSON.parse(fs.readFileSync(filename));
  4. }
  5. // good json file
  6. console.log(loadJSONSync('good.json'));
  7. // non-existent file, so fs.readFileSync fails
  8. try {
  9. console.log(loadJSONSync('absent.json'));
  10. }
  11. catch (err) {
  12. console.log('absent.json error', err.message);
  13. }
  14. // invalid json file i.e. the file exists but contains invalid JSON so JSON.parse fails
  15. try {
  16. console.log(loadJSONSync('invalid.json'));
  17. }
  18. catch (err) {
  19. console.log('invalid.json error', err.message);
  20. }

There are three behaviors of this simple loadJSONSync function, a valid return value, a file system error or a JSON.parse error. We handle the errors with a simple try/catch as you are used to when doing synchronous programming in other languages. Now let’s make a good async version of such a function. A decent initial attempt with a trivial error checking logic would be as follows:

  1. import fs = require('fs');
  2. // A decent initial attempt .... but not correct. We explain the reasons below
  3. function loadJSON(filename: string, cb: (error: Error, data: any) => void) {
  4. fs.readFile(filename, function (err, data) {
  5. if (err) cb(err);
  6. else cb(null, JSON.parse(data));
  7. });
  8. }

Simple enough, it takes a callback, passes any file system errors to the callback. If no file system errors, it returns the JSON.parse result. A few points to keep in mind when working with async functions based on callbacks are:

  1. Never call the callback twice.
  2. Never throw an error.

This simple function however fails to accommodate for point two. In fact JSON.parse throws an error if it is passed bad JSON and the callback never gets called and the application crashes. This is demonstrated in the below example:

  1. import fs = require('fs');
  2. // A decent initial attempt .... but not correct
  3. function loadJSON(filename: string, cb: (error: Error, data: any) => void) {
  4. fs.readFile(filename, function (err, data) {
  5. if (err) cb(err);
  6. else cb(null, JSON.parse(data));
  7. });
  8. }
  9. // load invalid json
  10. loadJSON('invalid.json', function (err, data) {
  11. // This code never executes
  12. if (err) console.log('bad.json error', err.message);
  13. else console.log(data);
  14. });

A naive attempt at fixing this would be to wrap the JSON.parse in a try catch as shown in the below example:

  1. import fs = require('fs');
  2. // A better attempt ... but still not correct
  3. function loadJSON(filename: string, cb: (error: Error) => void) {
  4. fs.readFile(filename, function (err, data) {
  5. if (err) {
  6. cb(err);
  7. }
  8. else {
  9. try {
  10. cb(null, JSON.parse(data));
  11. }
  12. catch (err) {
  13. cb(err);
  14. }
  15. }
  16. });
  17. }
  18. // load invalid json
  19. loadJSON('invalid.json', function (err, data) {
  20. if (err) console.log('bad.json error', err.message);
  21. else console.log(data);
  22. });

However there is a subtle bug in this code. If the callback (cb), and not JSON.parse, throws an error, since we wrapped it in a try/catch, the catch executes and we call the callback again i.e. the callback gets called twice! This is demonstrated in the example below:

  1. import fs = require('fs');
  2. function loadJSON(filename: string, cb: (error: Error) => void) {
  3. fs.readFile(filename, function (err, data) {
  4. if (err) {
  5. cb(err);
  6. }
  7. else {
  8. try {
  9. cb(null, JSON.parse(data));
  10. }
  11. catch (err) {
  12. cb(err);
  13. }
  14. }
  15. });
  16. }
  17. // a good file but a bad callback ... gets called again!
  18. loadJSON('good.json', function (err, data) {
  19. console.log('our callback called');
  20. if (err) console.log('Error:', err.message);
  21. else {
  22. // let's simulate an error by trying to access a property on an undefined variable
  23. var foo;
  24. // The following code throws `Error: Cannot read property 'bar' of undefined`
  25. console.log(foo.bar);
  26. }
  27. });
  1. $ node asyncbadcatchdemo.js
  2. our callback called
  3. our callback called
  4. Error: Cannot read property 'bar' of undefined

This is because our loadJSON function wrongfully wrapped the callback in a try block. There is a simple lesson to remember here.

Simple lesson: Contain all your sync code in a try catch, except when you call the callback.

Following this simple lesson, we have a fully functional async version of loadJSON as shown below:

  1. import fs = require('fs');
  2. function loadJSON(filename: string, cb: (error: Error) => void) {
  3. fs.readFile(filename, function (err, data) {
  4. if (err) return cb(err);
  5. // Contain all your sync code in a try catch
  6. try {
  7. var parsed = JSON.parse(data);
  8. }
  9. catch (err) {
  10. return cb(err);
  11. }
  12. // except when you call the callback
  13. return cb(null, parsed);
  14. });
  15. }

Admittedly this is not hard to follow once you’ve done it a few times but nonetheless it’s a lot of boiler plate code to write simply for good error handling. Now let’s look at a better way to tackle asynchronous JavaScript using promises.

Creating a Promise

A promise can be either pending or fulfilled or rejected.

promise states and fates

Let’s look at creating a promise. It’s a simple matter of calling new on Promise (the promise constructor). The promise constructor is passed resolve and reject functions for settling the promise state:

  1. const promise = new Promise((resolve, reject) => {
  2. // the resolve / reject functions control the fate of the promise
  3. });

Subscribing to the fate of the promise

The promise fate can be subscribed to using .then (if resolved) or .catch (if rejected).

  1. const promise = new Promise((resolve, reject) => {
  2. resolve(123);
  3. });
  4. promise.then((res) => {
  5. console.log('I get called:', res === 123); // I get called: true
  6. });
  7. promise.catch((err) => {
  8. // This is never called
  9. });
  1. const promise = new Promise((resolve, reject) => {
  2. reject(new Error("Something awful happened"));
  3. });
  4. promise.then((res) => {
  5. // This is never called
  6. });
  7. promise.catch((err) => {
  8. console.log('I get called:', err.message); // I get called: 'Something awful happened'
  9. });

TIP: Promise Shortcuts

  • Quickly creating an already resolved promise: Promise.resolve(result)
  • Quickly creating an already rejected promise: Promise.reject(error)

Chain-ability of Promises

The chain-ability of promises is the heart of the benefit that promises provide. Once you have a promise, from that point on, you use the then function to create a chain of promises.

  • If you return a promise from any function in the chain, .then is only called once the value is resolved:
  1. Promise.resolve(123)
  2. .then((res) => {
  3. console.log(res); // 123
  4. return 456;
  5. })
  6. .then((res) => {
  7. console.log(res); // 456
  8. return Promise.resolve(123); // Notice that we are returning a Promise
  9. })
  10. .then((res) => {
  11. console.log(res); // 123 : Notice that this `then` is called with the resolved value
  12. return 123;
  13. })
  • You can aggregate the error handling of any preceding portion of the chain with a single catch:
  1. // Create a rejected promise
  2. Promise.reject(new Error('something bad happened'))
  3. .then((res) => {
  4. console.log(res); // not called
  5. return 456;
  6. })
  7. .then((res) => {
  8. console.log(res); // not called
  9. return 123;
  10. })
  11. .then((res) => {
  12. console.log(res); // not called
  13. return 123;
  14. })
  15. .catch((err) => {
  16. console.log(err.message); // something bad happened
  17. });
  • The catch actually returns a new promise (effectively creating a new promise chain):
  1. // Create a rejected promise
  2. Promise.reject(new Error('something bad happened'))
  3. .then((res) => {
  4. console.log(res); // not called
  5. return 456;
  6. })
  7. .catch((err) => {
  8. console.log(err.message); // something bad happened
  9. return 123;
  10. })
  11. .then((res) => {
  12. console.log(res); // 123
  13. })
  • Any synchronous errors thrown in a then (or catch) result in the returned promise to fail:
  1. Promise.resolve(123)
  2. .then((res) => {
  3. throw new Error('something bad happened'); // throw a synchronous error
  4. return 456;
  5. })
  6. .then((res) => {
  7. console.log(res); // never called
  8. return Promise.resolve(789);
  9. })
  10. .catch((err) => {
  11. console.log(err.message); // something bad happened
  12. })
  • Only the relevant (nearest tailing) catch is called for a given error (as the catch starts a new promise chain).
  1. Promise.resolve(123)
  2. .then((res) => {
  3. throw new Error('something bad happened'); // throw a synchronous error
  4. return 456;
  5. })
  6. .catch((err) => {
  7. console.log('first catch: ' + err.message); // something bad happened
  8. return 123;
  9. })
  10. .then((res) => {
  11. console.log(res); // 123
  12. return Promise.resolve(789);
  13. })
  14. .catch((err) => {
  15. console.log('second catch: ' + err.message); // never called
  16. })
  • A catch is only called in case of an error in the preceeding chain:
  1. Promise.resolve(123)
  2. .then((res) => {
  3. return 456;
  4. })
  5. .catch((err) => {
  6. console.log("HERE"); // never called
  7. })

The fact that:

  • errors jump to the tailing catch (and skip any middle then calls) and
  • synchronous errors also get caught by any tailing catch.

effectively provides us with an async programming paradigm that allows better error handling than raw callbacks. More on this below.

TypeScript and promises

The great thing about TypeScript is that it understands the flow of values through a promise chain:

  1. Promise.resolve(123)
  2. .then((res) => {
  3. // res is inferred to be of type `number`
  4. return true;
  5. })
  6. .then((res) => {
  7. // res is inferred to be of type `boolean`
  8. });

Of course it also understands unwrapping any function calls that might return a promise:

  1. function iReturnPromiseAfter1Second(): Promise<string> {
  2. return new Promise((resolve) => {
  3. setTimeout(() => resolve("Hello world!"), 1000);
  4. });
  5. }
  6. Promise.resolve(123)
  7. .then((res) => {
  8. // res is inferred to be of type `number`
  9. return iReturnPromiseAfter1Second(); // We are returning `Promise<string>`
  10. })
  11. .then((res) => {
  12. // res is inferred to be of type `string`
  13. console.log(res); // Hello world!
  14. });

Converting a callback style function to return a promise

Just wrap the function call in a promise and

  • reject if an error occurs,
  • resolve if it is all good.

E.g. let’s wrap fs.readFile:

  1. import fs = require('fs');
  2. function readFileAsync(filename: string): Promise<any> {
  3. return new Promise((resolve,reject) => {
  4. fs.readFile(filename,(err,result) => {
  5. if (err) reject(err);
  6. else resolve(result);
  7. });
  8. });
  9. }

Revisiting the JSON example

Now let’s revisit our loadJSON example and rewrite an async version that uses promises. All that we need to do is read the file contents as a promise, then parse them as JSON and we are done. This is illustrated in the below example:

  1. function loadJSONAsync(filename: string): Promise<any> {
  2. return readFileAsync(filename) // Use the function we just wrote
  3. .then(function (res) {
  4. return JSON.parse(res);
  5. });
  6. }

Usage (notice how similar it is to the original sync version introduced at the start of this section ?):

  1. // good json file
  2. loadJSONAsync('good.json')
  3. .then(function (val) { console.log(val); })
  4. .catch(function (err) {
  5. console.log('good.json error', err.message); // never called
  6. })
  7. // non-existent json file
  8. .then(function () {
  9. return loadJSONAsync('absent.json');
  10. })
  11. .then(function (val) { console.log(val); }) // never called
  12. .catch(function (err) {
  13. console.log('absent.json error', err.message);
  14. })
  15. // invalid json file
  16. .then(function () {
  17. return loadJSONAsync('invalid.json');
  18. })
  19. .then(function (val) { console.log(val); }) // never called
  20. .catch(function (err) {
  21. console.log('bad.json error', err.message);
  22. });

The reason why this function was simpler is because the “loadFile(async) + JSON.parse (sync) => catch“ consolidation was done by the promise chain. Also the callback was not called by us but called by the promise chain so we didn’t have the chance of making the mistake of wrapping it in a try/catch.

Parallel control flow

We have seen how trivial doing a serial sequence of async tasks is with promises. It is simply a matter of chaining then calls.

However you might potentially want to run a series of async tasks and then do something with the results of all of these tasks. Promise provides a static Promise.all function that you can use to wait for n number of promises to complete. You provide it with an array of n promises and it gives you an array of n resolved values. Below we show Chaining as well as Parallel:

  1. // an async function to simulate loading an item from some server
  2. function loadItem(id: number): Promise<{ id: number }> {
  3. return new Promise((resolve) => {
  4. console.log('loading item', id);
  5. setTimeout(() => { // simulate a server delay
  6. resolve({ id: id });
  7. }, 1000);
  8. });
  9. }
  10. // Chaining
  11. let item1, item2;
  12. loadItem(1)
  13. .then((res) => {
  14. item1 = res;
  15. return loadItem(2);
  16. })
  17. .then((res) => {
  18. item2 = res;
  19. console.log('done');
  20. }); // overall time will be around 2s
  21. // Parallel
  22. Promise.all([loadItem(1), loadItem(2)])
  23. .then((res) => {
  24. [item1, item2] = res;
  25. console.log('done');
  26. }); // overall time will be around 1s

Sometimes, you want to run a series of async tasks, but you get all you need as long as any one of these tasks is settled. Promise provides a static Promise.race function for this scenario:

  1. var task1 = new Promise(function(resolve, reject) {
  2. setTimeout(resolve, 1000, 'one');
  3. });
  4. var task2 = new Promise(function(resolve, reject) {
  5. setTimeout(resolve, 2000, 'two');
  6. });
  7. Promise.race([task1, task2]).then(function(value) {
  8. console.log(value); // "one"
  9. // Both resolve, but task1 resolves faster
  10. });

Converting callback functions to promise

The most reliable way to do this is to hand write it. e.g. converting setTimeout into a promisified delay function is super easy:

  1. const delay = (ms: number) => new Promise(res => setTimeout(res, ms));

Note that there is a handy dandy function in NodeJS that does this node style function => promise returning function magic for you:

  1. /** Sample usage */
  2. import fs = require('fs');
  3. import util = require('util');
  4. const readFile = util.promisify1(fs.readFile);