Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
MR414N-ID
GitHub Repository: MR414N-ID/botku2
Path: blob/master/node_modules/@protobufjs/aspromise/index.js
1126 views
1
"use strict";
2
module.exports = asPromise;
3
4
/**
5
* Callback as used by {@link util.asPromise}.
6
* @typedef asPromiseCallback
7
* @type {function}
8
* @param {Error|null} error Error, if any
9
* @param {...*} params Additional arguments
10
* @returns {undefined}
11
*/
12
13
/**
14
* Returns a promise from a node-style callback function.
15
* @memberof util
16
* @param {asPromiseCallback} fn Function to call
17
* @param {*} ctx Function context
18
* @param {...*} params Function arguments
19
* @returns {Promise<*>} Promisified function
20
*/
21
function asPromise(fn, ctx/*, varargs */) {
22
var params = new Array(arguments.length - 1),
23
offset = 0,
24
index = 2,
25
pending = true;
26
while (index < arguments.length)
27
params[offset++] = arguments[index++];
28
return new Promise(function executor(resolve, reject) {
29
params[offset] = function callback(err/*, varargs */) {
30
if (pending) {
31
pending = false;
32
if (err)
33
reject(err);
34
else {
35
var params = new Array(arguments.length - 1),
36
offset = 0;
37
while (offset < params.length)
38
params[offset++] = arguments[offset];
39
resolve.apply(null, params);
40
}
41
}
42
};
43
try {
44
fn.apply(ctx || null, params);
45
} catch (err) {
46
if (pending) {
47
pending = false;
48
reject(err);
49
}
50
}
51
});
52
}
53
54