@gabi-bizdoc/promise-result
v1.0.2
Published
This is a minimalist library that aims to improve the quality of life when working with promises while fully embracing typescript.
Downloads
2
Maintainers
Readme
Promise result
Introduction
This is a minimalist library that aims to improve the quality of life when working with promises while fully embracing typescript.
Promise.all
will halt upon encountering the first failure, but the remaining promises will still be processed.
In contrast, PromiseResult.all
will cast the promises into result objects first ensuring that all promises have finished.
This can be useful in complex scenarios where it's important to know the final state of each promise. For example, when implementing error handling and rollback mechanism
Installation
npm i @gabi-bizdoc/promise-result
Examples
const result = await PromiseResult.from(promise);
if(result.succeeded) {
console.log(result.value);
} else {
console.error(result.error);
}
const promise1 = Promise.resolve(3);
const promise2 = 42;
const promise3 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, 'foo');
});
const promise4 = Promise.resolve("hello world");
const results = await PromiseResult.all([promise1, promise2, promise3, promise4] as const);
// const values = PromiseResult.extract(results);
// typescript will prevent us from using the results without verifying
if(PromiseResult.didAllSucceeded(results)) {
// here we can access the results
const result2 = results[2].value
const values = PromiseResult.extract(results);
// here values will infer the type: [number, 42, unknown, string]
} else {
// something went wrong
results.filter(isSuccess).map(async (t) => {
// t.value
// Note that this only works if the types are the same. But they can be cast if necessary
})
}