.gitignore added
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-prettier / node_modules / trough / wrap.js
1 'use strict'
2
3 var slice = [].slice
4
5 module.exports = wrap
6
7 // Wrap `fn`.
8 // Can be sync or async; return a promise, receive a completion handler, return
9 // new values and errors.
10 function wrap(fn, callback) {
11   var invoked
12
13   return wrapped
14
15   function wrapped() {
16     var params = slice.call(arguments, 0)
17     var callback = fn.length > params.length
18     var result
19
20     if (callback) {
21       params.push(done)
22     }
23
24     try {
25       result = fn.apply(null, params)
26     } catch (error) {
27       // Well, this is quite the pickle.
28       // `fn` received a callback and invoked it (thus continuing the pipeline),
29       // but later also threw an error.
30       // We’re not about to restart the pipeline again, so the only thing left
31       // to do is to throw the thing instead.
32       if (callback && invoked) {
33         throw error
34       }
35
36       return done(error)
37     }
38
39     if (!callback) {
40       if (result && typeof result.then === 'function') {
41         result.then(then, done)
42       } else if (result instanceof Error) {
43         done(result)
44       } else {
45         then(result)
46       }
47     }
48   }
49
50   // Invoke `next`, only once.
51   function done() {
52     if (!invoked) {
53       invoked = true
54
55       callback.apply(null, arguments)
56     }
57   }
58
59   // Invoke `done` with one value.
60   // Tracks if an error is passed, too.
61   function then(value) {
62     done(null, value)
63   }
64 }