3 let call = module.exports = {
9 * Calls a function with the given arguments, and ensures that the error-first callback is _always_
10 * invoked exactly once, even if the function throws an error.
12 * @param {function} fn - The function to invoke
13 * @param {...*} args - The arguments to pass to the function. The final argument must be a callback function.
15 function safeCall (fn, args) {
16 // Get the function arguments as an array
17 args = Array.prototype.slice.call(arguments, 1);
19 // Replace the callback function with a wrapper that ensures it will only be called once
20 let callback = call.once(args.pop());
32 * Returns a wrapper function that ensures the given callback function is only called once.
33 * Subsequent calls are ignored, unless the first argument is an Error, in which case the
36 * @param {function} fn - The function that should only be called once
39 function callOnce (fn) {
40 let fulfilled = false;
42 return function onceWrapper (err) {
45 return fn.apply(this, arguments);
48 // The callback has already been called, but now an error has occurred
49 // (most likely inside the callback function). So re-throw the error,
50 // so it gets handled further up the call stack