Home Blog CV Projects Patterns Notes Book Colophon Search

Callbacks

The node syntax for async calls tends to be:

getUser(token, (err, firstName, lastName) => {
    if (err) { throw err };
    // Do something with firstName and lastName
});

Where getUser is an asynchronous API call that is passed a token. The second argument is a callback whereerr is null if the call succeeded and an instance of Error containing a message otherwise and the other arguments represent the successful result of the calling the function.

Notice that the callback throws an error if one occurred in the API call.

An implementation might look like this:

function getUser(token, callback) {
    // Don't throw errors here, use the callback
    if (!token) {
        callback(new Error("Invalid token"));
    } else {
        callback(null, "james", "gardner");
});

Notice that the API implementation doesn't throw an error, it calls the callback with the error as the first argument.

There might be zero, one, two or more successful result arguments. In this case there are two named firstName and lastName. It is important to throw an error if something goes wrong and the callback gets an err argument that isn't null.

The convention seems to be to use err as the name of the error, callback as the name of the callback. If there is just one success argument it is often named result, otherwise the arguments should be named to reflect what they are.

Pros: It is what node has standardised on Cons: Tricky to get error handling right, complex logic hard to implement without third part libraries

Copyright James Gardner 1996-2020 All Rights Reserved. Admin.