1 | ;
|
2 |
|
3 | Object.defineProperty(exports, "__esModule", {
|
4 | value: true
|
5 | });
|
6 | exports.promisify = promisify;
|
7 |
|
8 | // Copyright 2017-2022 @polkadot/util authors & contributors
|
9 | // SPDX-License-Identifier: Apache-2.0
|
10 |
|
11 | /**
|
12 | * @name promisify
|
13 | * @summary Wraps an async callback into a `Promise`
|
14 | * @description
|
15 | * Wraps the supplied async function `fn` that has a standard JS callback `(error: Error, result: any)` into a `Promise`, passing the supplied parameters. When `error` is set, the Promise is rejected, else the Promise resolves with the `result` value.
|
16 | * @example
|
17 | * <BR>
|
18 | *
|
19 | * ```javascript
|
20 | * const { promisify } from '@polkadot/util';
|
21 | *
|
22 | * await promisify(null, ((a, cb) => cb(null, a), true); // resolves with `true`
|
23 | * await promisify(null, (cb) => cb(new Error('error!'))); // rejects with `error!`
|
24 | * ```
|
25 | */
|
26 | // eslint-disable-next-line @typescript-eslint/no-explicit-any
|
27 | function promisify(self, fn) {
|
28 | for (var _len = arguments.length, params = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
|
29 | params[_key - 2] = arguments[_key];
|
30 | }
|
31 |
|
32 | return new Promise((resolve, reject) => {
|
33 | fn.apply(self, params.concat((error, result) => {
|
34 | if (error) {
|
35 | reject(error);
|
36 | } else {
|
37 | resolve(result);
|
38 | }
|
39 | }));
|
40 | });
|
41 | } |
\ | No newline at end of file |