An Async implementation of the awesome https://github.com/vultix/ts-results.
Installations
npm install ts-async-results
Developer Guide
Typescript
Yes
Module System
CommonJS
Node Version
16.14.0
NPM Version
8.3.1
Score
71.4
Supply Chain
98.3
Quality
76
Maintenance
100
Vulnerability
100
License
Releases
Unable to fetch releases
Contributors
Unable to fetch Contributors
Languages
TypeScript (98.31%)
JavaScript (1.69%)
Developer
movesthatmatter
Download Statistics
Total Downloads
31,093
Last Day
1
Last Week
33
Last Month
254
Last Year
11,240
GitHub Statistics
44 Stars
62 Commits
2 Forks
2 Watching
1 Branches
1 Contributors
Bundle Size
10.74 kB
Minified
2.50 kB
Minified + Gzipped
Package Meta Information
Latest Version
0.7.10
Package Id
ts-async-results@0.7.10
Unpacked Size
32.26 kB
Size
7.66 kB
File Count
10
NPM Version
8.3.1
Node Version
16.14.0
Publised On
15 Jun 2023
Total Downloads
Cumulative downloads
Total Downloads
31,093
Last day
0%
1
Compared to previous day
Last week
-26.7%
33
Compared to previous week
Last month
-30%
254
Compared to previous month
Last year
-27.4%
11,240
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
Dependencies
1
Dev Dependencies
4
ts-async-results
An Async implementation of the awesome ts-results.
For an intro into the Result's API check out the above link or Rust's own Result API.
This library only addresses the Async component of the Result.
LOOKING FOR CONTRIBUTORS
Contents
Installation
1$ npm install ts-async-results
or
1$ yarn add ts-async-results
Usage
1import { AsyncResultWrapper, AsyncErr, AsyncOk } from 'ts-async-results';
Creation
1let okAsyncResult: AsyncResult<number, Error> = new AsyncOk(10); 2let okResult2 = AsyncOk<number, Error>(10); // Exact same as above 3 4let errorResult: AsyncResult<number, Error> = new AsyncOk(new Error('bad number!')); 5let errorResult2 = new AsyncOk<number, Error>(new Error('bad number!')); // Exact same as above 6
Wrap other Result or Async Result
1 2// From Result 3new AsyncResultWrapper(new Ok(10)); 4 5// From Result Function 6new AsyncResultWrapper(() => new Ok(10)); 7 8// From Result Async Function 9let okFromResultAsyncFn = new AsyncResultWrapper(async () => { 10 await delay(1); 11 12 return new Ok(10) 13}); 14 15// From Async 16new AsyncResultWrapper(new AsyncOk(10)); 17 18// From Async Result Function 19new AsyncResultWrapper(() => new AsyncOk(10)); 20 21// From Async Result Async Function :) 22new AsyncResultWrapper(async () => { 23 await delay(1); 24 25 return new AsyncOk(10) 26}); 27 28// Works in the same way with AsyncErr or the alias AsyncReult.toAsyncResult()
Map and MapErr
1const httpAsyncResult = new AsyncResultWrapper(async () => { 2 try { 3 const { data } = await http.get('/api'); 4 5 return new Ok(data) 6 } catch (e) { 7 return new Err('BadRequest'); 8 } 9 }); 10 11httpAsyncResult 12 .map((myData) => { 13 // do stuff with the data 14 }) 15 .mapErr((err) => { 16 console.error(err); 17 });
Flatmap
1const getResourceAsyncResult = () => new AsyncResultWrapper(async () => { 2 try { 3 const { data } = await http.get('/api'); 4 5 return new Ok(data) 6 } catch (e) { 7 return new Err('BadRequest'); 8 } 9 }); 10 11const postResourceAndAnotherAsyncResult = (id: string) => new AsyncResultWrapper(async () => { 12 try { 13 const { data } = await http.post('/api', { id }); 14 15 return new Ok(data) 16 } catch (e) { 17 return new Err('BadRequest'); 18 } 19 }); 20 21 22getResourceAsyncResult() 23 .flatMap((myData) => { 24 // do some more async stuff with the data and return another AsyncResult 25 return postResourceAndAnotherAsyncResult(myData.id); 26 }) 27 .map((myData) => { 28 // do stuff with the data 29 }) 30 .mapErr((err) => { 31 console.error(err); 32 });
FlatMapErr
1 2const getResourceAsyncResultWithRetry = () => new AsyncResultWrapper(async () => { 3 try { 4 const { data } = await http.get('/api'); 5 6 return new Ok(data) 7 } catch (e) { 8 return new Err('BadRequest'); 9 } 10 }) 11 .flatMapErr((err) => { 12 // you can intercept an Err path and transform it into a (potential) Ok path 13 14 if (err === 'CONNECTION_FAILED') { 15 const retryAttemptAsyncResult = getResourceAsyncResult(); 16 17 18 // If the attempt failed due to a network error automatically retry 19 // NOTE: Don't use this code in production as it's veeeery inefficient! 20 // It's only meant for demonstration purposes. 21 return retryAttemptAsyncResult; 22 } 23 else { 24 // We always return back an AsyncResult 25 return new AsyncErr(err); 26 } 27 }); 28 29getResourceAsyncResultWithRetry() 30 .map((myData) => { 31 // do stuff with the data 32 }) 33 .mapErr((err) => { 34 console.error(err); 35 });
Expect
To use Expect
we make use of the fact that an AsyncResult resolves to a simple Result.
1let goodAsyncResult = new AsyncOk(1); 2let badAsyncResult = new AsyncErr("something went wrong"); 3 4let goodResult = (await goodAsyncResult.resolve()); 5let badResult = (await goodAsyncResult.resolve()); 6 7goodResult.expect('goodResult should be a number'); // 1 8badResult.expect('badResult should be a number'); // throws Error("badResult should be a number - Error: something went wrong")
Empty
1function checkIsValid(isValid: boolean): AsyncResult<void, Error> { 2 if (isValid) { 3 return AsyncOk.EMPTY; 4 } else { 5 return new AsyncErr("Not valid"); 6 } 7}
Resolve
Calling myAsyncResult.resolve()
transforms it into a Promise<Result<T, E>>
Ok Path
1let asyncResult = new AsyncOk(1); 2 3let result = (await goodAsyncResult.resolve()); 4 5console.log(result.val); // 1
Error Path
Note: Calling resolve()
does NOT throw when the value is an Error. See ResolveUnwrap if you need that behavior
1let asyncResult = new AsyncErr('SimpleErr'); 2 3let result = (await goodAsyncResult.resolve()); 4 5console.log(result.val); // SimpleErr
Unwrap
To use Unwrap
we make use of the fact that an AsyncResult resolves to a simple Result.
1let goodAsyncResult = new AsyncOk(1); 2let badAsyncResult = new AsyncErr("something went wrong"); 3 4let goodResult = (await goodAsyncResult.resolve()); 5let badResult = (await goodAsyncResult.resolve()); 6 7goodResult.unwrap(); // 1 8badResult.unwrap(); // throws Error("something went wrong")
UnwrapOr
To use UnwrapOr
we make use of the fact that an AsyncResult resolves to a simple Result.
1let goodAsyncResult = new AsyncOk(1); 2let badAsyncResult = new AsyncErr("something went wrong"); 3 4let goodResult = (await goodAsyncResult.resolve()); 5let badResult = (await goodAsyncResult.resolve()); 6 7let goodResult = Ok(1); 8let badResult = Err(new Error("something went wrong")); 9 10goodResult.unwrapOr(5); // 1 11badResult.unwrapOr(5); // 5
ResolveUnwrap
Combines Resolve and Unwrap functionalities.
1let goodAsyncResult = new AsyncOk(1); 2console.log(await goodAsyncResult.resolveUnwrap()); // 1 3 4let badAsyncResult = new AsyncErr("something went wrong"); 5console.log(await badAsyncResult.resolveUnwrap()); // throws Error("something went wrong")
ResolveUnwrapOr
Similar to "ResolveUnwrap" but provides a fallback for the Error path. The Ok path remains unaffected!
1let goodAsyncResult = new AsyncOk(1); 2console.log(await goodAsyncResult.resolveUnwrapor(5)); // 1 3 4let badAsyncResult = new AsyncErr("something went wrong"); 5console.log(await badAsyncResult.resolveUnwrapOr(5)); // 5
Combining Results
ts-async-results
has one helper function for operating over n Result
objects.
AsyncResult.all
Either returns all of the Ok
values, or the first Err
value
Ok Path
1 2const allResult = AsyncResult.all( 3 new AsyncOk(2), 4 new AsyncOk('a string'), 5); 6 7(await allResult.resolve()).unwrap()) // [2, 'a string'];
Err Path
1 2const allResult = AsyncResult.all( 3 new AsyncOk(2), 4 new AsyncErr('AnError'), 5); 6 7(await allResult.resolve()).unwrap()) // AnError
AsyncResult.any
TBD
No vulnerabilities found.
No security vulnerabilities found.
Gathering detailed insights and metrics for ts-async-results