UNPKG

1.03 kBJavaScriptView Raw
1// Copyright 2017-2022 @polkadot/util authors & contributors
2// SPDX-License-Identifier: Apache-2.0
3
4/**
5 * @name promisify
6 * @summary Wraps an async callback into a `Promise`
7 * @description
8 * 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.
9 * @example
10 * <BR>
11 *
12 * ```javascript
13 * const { promisify } from '@polkadot/util';
14 *
15 * await promisify(null, ((a, cb) => cb(null, a), true); // resolves with `true`
16 * await promisify(null, (cb) => cb(new Error('error!'))); // rejects with `error!`
17 * ```
18 */
19// eslint-disable-next-line @typescript-eslint/no-explicit-any
20export function promisify(self, fn, ...params) {
21 return new Promise((resolve, reject) => {
22 fn.apply(self, params.concat((error, result) => {
23 if (error) {
24 reject(error);
25 } else {
26 resolve(result);
27 }
28 }));
29 });
30}
\No newline at end of file