.gitignore added
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-prettier / node_modules / @mrmlnc / readdir-enhanced / lib / call.js
1 'use strict';
2
3 let call = module.exports = {
4   safe: safeCall,
5   once: callOnce,
6 };
7
8 /**
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.
11  *
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.
14  */
15 function safeCall (fn, args) {
16   // Get the function arguments as an array
17   args = Array.prototype.slice.call(arguments, 1);
18
19   // Replace the callback function with a wrapper that ensures it will only be called once
20   let callback = call.once(args.pop());
21   args.push(callback);
22
23   try {
24     fn.apply(null, args);
25   }
26   catch (err) {
27     callback(err);
28   }
29 }
30
31 /**
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
34  * error is thrown.
35  *
36  * @param {function} fn - The function that should only be called once
37  * @returns {function}
38  */
39 function callOnce (fn) {
40   let fulfilled = false;
41
42   return function onceWrapper (err) {
43     if (!fulfilled) {
44       fulfilled = true;
45       return fn.apply(this, arguments);
46     }
47     else if (err) {
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
51       throw err;
52     }
53   };
54 }