Problem
You want to be sure that a callback function is not accidentally called twice or more.
Ingredients
- the
return
keyword
Directions
-
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); }
-
Now assume that
someOtherFunction()
produces an error. What happens? The error is catched andcallback(error, null)
is executed. But additionallycallback(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 }
-
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; }
-
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 }
- Voilá, now if
someOtherFunction()
produces an error, the second callback is not called.
Alternative recipes
- Use promises.