X-Git-Url: https://git.immae.eu/?a=blobdiff_plain;f=shared%2Fcore-utils%2Fcommon%2Fpromises.ts;h=e3792d12e47b5df7d55807c2ba33a7aaecf1a70a;hb=0c9668f77901e7540e2c7045eb0f2974a4842a69;hp=f17221b97fb61841f7aeeb86c1d2cd4f6b9b4341;hpb=841cb202432a2abf538465f69953027973dc02aa;p=github%2FChocobozzz%2FPeerTube.git diff --git a/shared/core-utils/common/promises.ts b/shared/core-utils/common/promises.ts index f17221b97..e3792d12e 100644 --- a/shared/core-utils/common/promises.ts +++ b/shared/core-utils/common/promises.ts @@ -1,12 +1,12 @@ -function isPromise (value: T | Promise): value is Promise { +export function isPromise (value: T | Promise): value is Promise { return value && typeof (value as Promise).then === 'function' } -function isCatchable (value: any) { +export function isCatchable (value: any) { return value && typeof value.catch === 'function' } -function timeoutPromise (promise: Promise, timeoutMs: number) { +export function timeoutPromise (promise: Promise, timeoutMs: number) { let timer: ReturnType return Promise.race([ @@ -18,8 +18,41 @@ function timeoutPromise (promise: Promise, timeoutMs: number) { ]).finally(() => clearTimeout(timer)) } -export { - isPromise, - isCatchable, - timeoutPromise +export function promisify0 (func: (cb: (err: any, result: A) => void) => void): () => Promise { + return function promisified (): Promise { + return new Promise((resolve: (arg: A) => void, reject: (err: any) => void) => { + // eslint-disable-next-line no-useless-call + func.apply(null, [ (err: any, res: A) => err ? reject(err) : resolve(res) ]) + }) + } +} + +// Thanks to https://gist.github.com/kumasento/617daa7e46f13ecdd9b2 +export function promisify1 (func: (arg: T, cb: (err: any, result: A) => void) => void): (arg: T) => Promise { + return function promisified (arg: T): Promise { + return new Promise((resolve: (arg: A) => void, reject: (err: any) => void) => { + // eslint-disable-next-line no-useless-call + func.apply(null, [ arg, (err: any, res: A) => err ? reject(err) : resolve(res) ]) + }) + } +} + +// eslint-disable-next-line max-len +export function promisify2 (func: (arg1: T, arg2: U, cb: (err: any, result: A) => void) => void): (arg1: T, arg2: U) => Promise { + return function promisified (arg1: T, arg2: U): Promise { + return new Promise((resolve: (arg: A) => void, reject: (err: any) => void) => { + // eslint-disable-next-line no-useless-call + func.apply(null, [ arg1, arg2, (err: any, res: A) => err ? reject(err) : resolve(res) ]) + }) + } +} + +// eslint-disable-next-line max-len +export function promisify3 (func: (arg1: T, arg2: U, arg3: V, cb: (err: any, result: A) => void) => void): (arg1: T, arg2: U, arg3: V) => Promise { + return function promisified (arg1: T, arg2: U, arg3: V): Promise { + return new Promise((resolve: (arg: A) => void, reject: (err: any) => void) => { + // eslint-disable-next-line no-useless-call + func.apply(null, [ arg1, arg2, arg3, (err: any, res: A) => err ? reject(err) : resolve(res) ]) + }) + } }