Neues Node.js-Buch
Alle Artikel

Return after calling a callback

Problem

You want to be sure that a callback function is not accidentally called twice or more.

Ingredients

  • the return keyword

Directions

  1. Given: a function that accepts a callback function and calls it in two different places.

    function someFunction(callback) {
      let result = {};
      try {
        result = someOtherFunction();
      } catch(error) {
        callback(error, null);
      }
      callback(null, result);
    }
  2. Now assume that someOtherFunction() produces an error. What happens? The error is catched and callback(error, null) is executed. But additionally callback(null, result) is called as well. This is most likely not the intention.

    function someFunction(callback) {
      let result = {};
      try {
        result = someOtherFunction();  // (1) Produces an error
      } catch(error) {
        callback(error, null);         // (2) Gets called
      }
      callback(null, result);          // (3) Gets called as well
    }
  3. Solution: add return after calling callbacks.

    function someFunction(callback) {
      let result = {};
      try {
        result = someOtherFunction();  // (1) Produces an error
      } catch(error) {
        callback(error, null);         // (2) Gets called
        return;
      }
      callback(null, result);          // (3) Doesn't get called
      return;
    }
  4. Even better: add return before the call of the callback function.

    function someFunction(callback) {
      let result = {};
      try {
        result = someOtherFunction();  // (1) Produces an error
      } catch(error) {
        return callback(error, null);  // (2) Gets called
      }
      return callback(null, result);   // (3) Doesn't get called
    }
  5. Voilá, now if someOtherFunction() produces an error, the second callback is not called.

Alternative recipes

  • Use promises.