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