Skip to content

Instantly share code, notes, and snippets.

@jose8a
Created September 11, 2015 21:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jose8a/3e8285ecc6e12467d8f2 to your computer and use it in GitHub Desktop.
Save jose8a/3e8285ecc6e12467d8f2 to your computer and use it in GitHub Desktop.

Basic Callback Pattern

function shoutOutTo(param1, param2, callback) {
    alert('Holla, holla, holla!\nGiving a shoutOut to ' + param1);
    callback();
}

theHomie('Buster', function() {
    alert('Finished eating my sandwich.');
});

Callback is Optional

function mySandwich(param1, param2, callback) {
    alert('Started eating my sandwich.\n\nIt has: ' + param1 + ', ' + param2);
    if (callback) {
        callback();
    }
}

mySandwich('ham', 'cheese');

Ensuring Callback is a Function

function mySandwich(param1, param2, callback) {
    alert('Started eating my sandwich.\n\nIt has: ' + param1 + ', ' + param2);
    if (callback && typeof(callback) === "function") {
        callback();
    }
}

mySandwich('ham', 'cheese', 'vegetables');

Resources

Understand JS Callbacks and Use Them - JSIsSexy Callback Functions in JS Refactoring Out of Callback Hell Understanding Error-first Callbacks in NodeJS

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment