Last active
December 20, 2021 12:03
-
-
Save markodayan/aa8235ea6a8d31605aa3cea10b039d48 to your computer and use it in GitHub Desktop.
Asynchronising functional programming pattern example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Fn = (...args: any[]) => any; | |
function makeAsync<T extends Fn>(fn: Fn): (...args: Parameters<T>) => Promise<ReturnType<T>> { | |
return function (this: any, ...args: Parameters<T>): Promise<ReturnType<T>> { | |
return new Promise<ReturnType<T>>((res, rej) => { | |
try { | |
res(fn.call(this, ...args)); | |
} catch (e) { | |
rej(e); | |
} | |
}) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function makeAsync(fn) { | |
return function (...args) { | |
return new Promise((res, rej) => { | |
try { | |
res(fn.call(this, ...args)); | |
} catch (e) { | |
rej(e); | |
} | |
}) | |
} | |
} | |
// it can be used like this | |
const obj = { | |
value: 1, | |
add: makeAsync( | |
function (a) { | |
return this.value + a; | |
} | |
) | |
} | |
obj.add(2).then(r => console.log(r)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment