Skip to content

Instantly share code, notes, and snippets.

@jose8a
Created September 11, 2015 21:40
Show Gist options
  • Select an option

  • Save jose8a/3e8285ecc6e12467d8f2 to your computer and use it in GitHub Desktop.

Select an option

Save jose8a/3e8285ecc6e12467d8f2 to your computer and use it in GitHub Desktop.

Revisions

  1. jose8a created this gist Sep 11, 2015.
    42 changes: 42 additions & 0 deletions callbacks.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,42 @@
    ### Basic Callback Pattern
    ```javascript
    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
    ```javascript
    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
    ```javascript
    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](http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/)
    [Callback Functions in JS](http://www.impressivewebs.com/callback-functions-javascript/)
    [Refactoring Out of Callback Hell](http://callbackhell.com/)
    [Understanding Error-first Callbacks in NodeJS](http://fredkschott.com/post/2014/03/understanding-error-first-callbacks-in-node-js/)