Skip to content

Instantly share code, notes, and snippets.

@SparK-Cruz
Created January 18, 2023 04:42
Show Gist options
  • Save SparK-Cruz/62761d7e140f2168364937a08f222492 to your computer and use it in GitHub Desktop.
Save SparK-Cruz/62761d7e140f2168364937a08f222492 to your computer and use it in GitHub Desktop.
Pipe so you don't pile .catch handlers in Promises
export const pipe = function<T>(promise: Promise<T>, ...callbacks: ((value: T) => T|Promise<T>)[]): Promise<T> {
let subject = promise;
for (const i in callbacks) {
subject = subject.then(callbacks[i])
}
return subject;
}
const doSomething = function(): Promise<number> {
return new Promise((resolve, reject) => { resolve(5); });
}
pipe(
doSomething(),
(value) => value + 10,
(value) => value - 2,
(value) => value + 9,
(value) => value / 2,
)
.then(somethingElse)
.catch(handleErrors)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment