until-async 3.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +114 -0
- package/lib/index.d.ts +16 -0
- package/lib/index.js +24 -0
- package/lib/index.js.map +1 -0
- package/package.json +52 -0
- package/src/index.ts +26 -0
- package/src/until.test-d.ts +25 -0
- package/src/until.test.ts +20 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2021 Artem Zakharchenko
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
# `until-async`
|
|
2
|
+
|
|
3
|
+
Gracefully handle a Promise using `async`/`await`.
|
|
4
|
+
|
|
5
|
+
## Why?
|
|
6
|
+
|
|
7
|
+
With the addition of `async`/`await` keywords in ECMAScript 2017 the handling of Promises became much easier. However, one must keep in mind that the `await` keyword provides no standard error handling API. Consider this usage:
|
|
8
|
+
|
|
9
|
+
```js
|
|
10
|
+
async function getUser(id) {
|
|
11
|
+
const data = await fetchUser(id)
|
|
12
|
+
// Work with "data"...
|
|
13
|
+
}
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
In case `fetchUser()` throws an error, the entire `getUser()` function's scope will terminate. Because of this, it's recommended to implement error handling using `try`/`catch` block wrapping `await` expressions:
|
|
17
|
+
|
|
18
|
+
```js
|
|
19
|
+
async function getUser(id) {
|
|
20
|
+
let data = null
|
|
21
|
+
|
|
22
|
+
try {
|
|
23
|
+
data = await asyncAction()
|
|
24
|
+
} catch (error) {
|
|
25
|
+
console.error(error)
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Work with "data"...
|
|
29
|
+
}
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
While this is a semantically valid approach, constructing `try`/`catch` around each awaited operation may be tedious and get overlooked at times. Such error handling also introduces separate closures for execution and error scenarios of an asynchronous operation.
|
|
33
|
+
|
|
34
|
+
This library encapsulates the `try`/`catch` error handling in a utility function that does not create a separate closure and exposes a NodeJS-friendly API to work with errors and resolved data.
|
|
35
|
+
|
|
36
|
+
## Getting started
|
|
37
|
+
|
|
38
|
+
### Install
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
npm install until-async
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
### Usage
|
|
45
|
+
|
|
46
|
+
```js
|
|
47
|
+
import { until } from 'until-async'
|
|
48
|
+
|
|
49
|
+
async function getUserById(id) {
|
|
50
|
+
const [error, data] = await until(() => fetchUser(id))
|
|
51
|
+
|
|
52
|
+
if (error) {
|
|
53
|
+
return handleError(error)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
return data
|
|
57
|
+
}
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
### Usage with TypeScript
|
|
61
|
+
|
|
62
|
+
```ts
|
|
63
|
+
import { until } from 'until-async'
|
|
64
|
+
|
|
65
|
+
interface User {
|
|
66
|
+
firstName: string
|
|
67
|
+
age: number
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
interface UserFetchError {
|
|
71
|
+
type: 'FORBIDDEN' | 'NOT_FOUND'
|
|
72
|
+
message?: string
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function getUserById(id: string) {
|
|
76
|
+
const [error, data] = await until<UserFetchError, User>(() => fetchUser(id))
|
|
77
|
+
|
|
78
|
+
if (error) {
|
|
79
|
+
return handleError(error.type, error.message)
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return data.firstName
|
|
83
|
+
}
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## Frequently asked questions
|
|
87
|
+
|
|
88
|
+
### Why does `until` accept a function and not a `Promise` directly?
|
|
89
|
+
|
|
90
|
+
This has been intentionally introduced to await a single logical unit as opposed to a single `Promise`.
|
|
91
|
+
|
|
92
|
+
```js
|
|
93
|
+
// Notice how a single "until" invocation can handle
|
|
94
|
+
// a rather complex piece of logic. This way any rejections
|
|
95
|
+
// or exceptions happening within the given function
|
|
96
|
+
// can be handled via the same "error".
|
|
97
|
+
const [error, data] = until(async () => {
|
|
98
|
+
const user = await fetchUser()
|
|
99
|
+
const nextUser = normalizeUser(user)
|
|
100
|
+
const transaction = await saveModel('user', user)
|
|
101
|
+
|
|
102
|
+
invariant(transaction.status === 'OK', 'Saving user failed')
|
|
103
|
+
|
|
104
|
+
return transaction.result
|
|
105
|
+
})
|
|
106
|
+
|
|
107
|
+
if (error) {
|
|
108
|
+
// Handle any exceptions happened within the function.
|
|
109
|
+
}
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
## Special thanks
|
|
113
|
+
|
|
114
|
+
- [giuseppegurgone](https://twitter.com/giuseppegurgone) for the discussion about the original `until` API.
|
package/lib/index.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
//#region src/index.d.ts
|
|
2
|
+
type UntilResult<RejectionReason, ResolveData> = [reason: RejectionReason, data: null] | [reason: null, data: ResolveData];
|
|
3
|
+
/**
|
|
4
|
+
* Gracefully handles a callback that returns a promise.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* await until(() => Promise.resolve(123))
|
|
8
|
+
* // [null, 123]
|
|
9
|
+
*
|
|
10
|
+
* await until(() => Promise.reject(new Error('Oops!')))
|
|
11
|
+
* // [new Error('Oops!'), null]
|
|
12
|
+
*/
|
|
13
|
+
declare function until<RejectionReason = Error, ResolveData = unknown>(callback: () => Promise<ResolveData>): Promise<UntilResult<RejectionReason, ResolveData>>;
|
|
14
|
+
//#endregion
|
|
15
|
+
export { UntilResult, until };
|
|
16
|
+
//# sourceMappingURL=index.d.ts.map
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
//#region src/index.ts
|
|
2
|
+
/**
|
|
3
|
+
* Gracefully handles a callback that returns a promise.
|
|
4
|
+
*
|
|
5
|
+
* @example
|
|
6
|
+
* await until(() => Promise.resolve(123))
|
|
7
|
+
* // [null, 123]
|
|
8
|
+
*
|
|
9
|
+
* await until(() => Promise.reject(new Error('Oops!')))
|
|
10
|
+
* // [new Error('Oops!'), null]
|
|
11
|
+
*/
|
|
12
|
+
async function until(callback) {
|
|
13
|
+
try {
|
|
14
|
+
return [null, await callback().catch((error) => {
|
|
15
|
+
throw error;
|
|
16
|
+
})];
|
|
17
|
+
} catch (error) {
|
|
18
|
+
return [error, null];
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
//#endregion
|
|
23
|
+
export { until };
|
|
24
|
+
//# sourceMappingURL=index.js.map
|
package/lib/index.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":["error: any"],"sources":["../src/index.ts"],"sourcesContent":["export type UntilResult<RejectionReason, ResolveData> =\n | [reason: RejectionReason, data: null]\n | [reason: null, data: ResolveData]\n\n/**\n * Gracefully handles a callback that returns a promise.\n *\n * @example\n * await until(() => Promise.resolve(123))\n * // [null, 123]\n *\n * await until(() => Promise.reject(new Error('Oops!')))\n * // [new Error('Oops!'), null]\n */\nexport async function until<RejectionReason = Error, ResolveData = unknown>(\n callback: () => Promise<ResolveData>,\n): Promise<UntilResult<RejectionReason, ResolveData>> {\n try {\n const data = await callback().catch((error) => {\n throw error\n })\n return [null, data]\n } catch (error: any) {\n return [error, null]\n }\n}\n"],"mappings":";;;;;;;;;;;AAcA,eAAsB,MACpB,UACoD;AACpD,KAAI;AAIF,SAAO,CAAC,MAHK,MAAM,UAAU,CAAC,OAAO,UAAU;AAC7C,SAAM;IACN,CACiB;UACZA,OAAY;AACnB,SAAO,CAAC,OAAO,KAAK"}
|
package/package.json
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
{
|
|
2
|
+
"type": "module",
|
|
3
|
+
"name": "until-async",
|
|
4
|
+
"version": "3.0.2",
|
|
5
|
+
"description": "Gracefully handle a Promise using async/await.",
|
|
6
|
+
"main": "./lib/index.js",
|
|
7
|
+
"types": "./lib/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./lib/index.d.ts",
|
|
11
|
+
"default": "./lib/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"homepage": "https://github.com/kettanaito/until-async",
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "git+https://github.com/kettanaito/until-async.git"
|
|
18
|
+
},
|
|
19
|
+
"author": {
|
|
20
|
+
"name": "Artem Zakharchenko",
|
|
21
|
+
"url": "https://github.com/kettanaito"
|
|
22
|
+
},
|
|
23
|
+
"license": "MIT",
|
|
24
|
+
"funding": "https://github.com/sponsors/kettanaito",
|
|
25
|
+
"files": [
|
|
26
|
+
"lib",
|
|
27
|
+
"src"
|
|
28
|
+
],
|
|
29
|
+
"keywords": [
|
|
30
|
+
"async",
|
|
31
|
+
"promise",
|
|
32
|
+
"handle",
|
|
33
|
+
"gracefully",
|
|
34
|
+
"tuple",
|
|
35
|
+
"util"
|
|
36
|
+
],
|
|
37
|
+
"devDependencies": {
|
|
38
|
+
"@ossjs/release": "^0.8.1",
|
|
39
|
+
"@rolldown/binding-darwin-arm64": "1.0.0-beta.38",
|
|
40
|
+
"publint": "^0.3.13",
|
|
41
|
+
"tsdown": "^0.15.3",
|
|
42
|
+
"typescript": "^5.9.2",
|
|
43
|
+
"vitest": "^3.2.4"
|
|
44
|
+
},
|
|
45
|
+
"scripts": {
|
|
46
|
+
"dev": "tsdown -w",
|
|
47
|
+
"test": "vitest",
|
|
48
|
+
"lint": "publint",
|
|
49
|
+
"build": "tsdown",
|
|
50
|
+
"release": "release publish"
|
|
51
|
+
}
|
|
52
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export type UntilResult<RejectionReason, ResolveData> =
|
|
2
|
+
| [reason: RejectionReason, data: null]
|
|
3
|
+
| [reason: null, data: ResolveData]
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Gracefully handles a callback that returns a promise.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* await until(() => Promise.resolve(123))
|
|
10
|
+
* // [null, 123]
|
|
11
|
+
*
|
|
12
|
+
* await until(() => Promise.reject(new Error('Oops!')))
|
|
13
|
+
* // [new Error('Oops!'), null]
|
|
14
|
+
*/
|
|
15
|
+
export async function until<RejectionReason = Error, ResolveData = unknown>(
|
|
16
|
+
callback: () => Promise<ResolveData>,
|
|
17
|
+
): Promise<UntilResult<RejectionReason, ResolveData>> {
|
|
18
|
+
try {
|
|
19
|
+
const data = await callback().catch((error) => {
|
|
20
|
+
throw error
|
|
21
|
+
})
|
|
22
|
+
return [null, data]
|
|
23
|
+
} catch (error: any) {
|
|
24
|
+
return [error, null]
|
|
25
|
+
}
|
|
26
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { until } from './index.js'
|
|
2
|
+
|
|
3
|
+
it('infers the data type if no type arguments were provided', async () => {
|
|
4
|
+
const [error, data] = await until(() => Promise.resolve(123))
|
|
5
|
+
|
|
6
|
+
if (error) {
|
|
7
|
+
expectTypeOf(error).toEqualTypeOf<Error>()
|
|
8
|
+
expectTypeOf(data).toEqualTypeOf<null>()
|
|
9
|
+
} else {
|
|
10
|
+
expectTypeOf(error).toEqualTypeOf<null>()
|
|
11
|
+
expectTypeOf(data).toEqualTypeOf<number>()
|
|
12
|
+
}
|
|
13
|
+
})
|
|
14
|
+
|
|
15
|
+
it('treats error/data as a discriminated union type', async () => {
|
|
16
|
+
const [error, data] = await until<Error, number>(() => Promise.resolve(123))
|
|
17
|
+
|
|
18
|
+
if (error) {
|
|
19
|
+
expectTypeOf(error).toEqualTypeOf<Error>()
|
|
20
|
+
expectTypeOf(data).toEqualTypeOf<null>()
|
|
21
|
+
} else {
|
|
22
|
+
expectTypeOf(error).toEqualTypeOf<null>()
|
|
23
|
+
expectTypeOf(data).toEqualTypeOf<number>()
|
|
24
|
+
}
|
|
25
|
+
})
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { until } from './index.js'
|
|
2
|
+
|
|
3
|
+
it('resolves with the value returned from the callback', async () => {
|
|
4
|
+
await expect(until(async () => 'value')).resolves.toEqual([null, 'value'])
|
|
5
|
+
await expect(until(() => Promise.resolve('value'))).resolves.toEqual([
|
|
6
|
+
null,
|
|
7
|
+
'value',
|
|
8
|
+
])
|
|
9
|
+
})
|
|
10
|
+
|
|
11
|
+
it('resolves with the error thrown in the callback', async () => {
|
|
12
|
+
await expect(
|
|
13
|
+
until(() => Promise.reject(new Error('error'))),
|
|
14
|
+
).resolves.toEqual([new Error('error'), null])
|
|
15
|
+
|
|
16
|
+
await expect(until(() => Promise.reject('custom reason'))).resolves.toEqual([
|
|
17
|
+
'custom reason',
|
|
18
|
+
null,
|
|
19
|
+
])
|
|
20
|
+
})
|