Created
January 18, 2023 04:42
-
-
Save SparK-Cruz/62761d7e140f2168364937a08f222492 to your computer and use it in GitHub Desktop.
Pipe so you don't pile .catch handlers in Promises
This file contains 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
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; | |
} |
This file contains 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
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