Skip to content

Instantly share code, notes, and snippets.

@markodayan
Last active December 20, 2021 12:03
Show Gist options
  • Save markodayan/aa8235ea6a8d31605aa3cea10b039d48 to your computer and use it in GitHub Desktop.
Save markodayan/aa8235ea6a8d31605aa3cea10b039d48 to your computer and use it in GitHub Desktop.
Asynchronising functional programming pattern example
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);
}
})
}
}
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