5.3 Callbacks

A callback is a function that is passed as an argument to another function, which is expected to call back (execute) the argument at some convenient time.

Getting Ready

All you need to implement this recipe is an installation of TypeScript 2.0 or higher and jQuery.

How to do it

We can pass a callback (a function) to another function as follows:

function doSomething(callback: () => void) {
  // do something...
  callback();
}

How it works

In TypeScript functions are first-class citizens. This means that we can use functions just like any other value. Functions can be assigned to variables:

const callback = function() {
	console.log('called back!');
};

Functions can also be passed as arguments to another function:

doSomething(callback);

In the preceding line we have passed the variable named callback but it is also possible to pass a function which has not been previously defined:

doSomething(function() {
	console.log('called back!');
});

Remember that you can use arrow functions to declare anonymous functions. This is especially useful when declaring callbacks as inline functions:

doSomething(() => console.log('called back!'));

There’s more

We will now try to implement something similar to the jQuery AJAX function from scratch. In this example two callbacks named success and error are passed to a function named ajax as part of an object literal named options:

interface IAjaxOptions {
    url: string,
    async: boolean,
    method: string,
    dataType: string,
    success: (data: any) => void,
    error: (error: any) => void
  }

function ajax(options: IAjaxOptions) {
    const request = new XMLHttpRequest();
    request.open(options.method, options.url, options.async);

    request.onload = function () {
      if (request.status >= 200 && request.status < 400) {
        // Success!
        let data = null;
        if (options.dataType === 'json') {
          data = JSON.parse(request.responseText);
        }
        options.success(data);
      }
      else {
        // We reached our target server, but it returned an error
        options.error(request.responseText);
      }
    };

    request.onerror = options.error;
    request.send();
  }

Source Code

Callbacks
Callbacks (AJAX)

See also

Please refer to the recipes about the XMLHttpRequest API and promises in this chapter to learn about more about the XMLHttpRequest API.


Shiv Kushwaha

Author/Programmer