promise-tuple 1.0.0 → 1.1.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/README.md CHANGED
@@ -121,15 +121,51 @@ const [error, data] = await promiseTuple<string, CustomError>(
121
121
  );
122
122
  ```
123
123
 
124
+ ### With Callbacks
125
+
126
+ You can optionally provide success and failure callbacks:
127
+
128
+ ```typescript
129
+ import promiseTuple from 'promise-tuple';
130
+
131
+ const [error, data] = await promiseTuple(
132
+ fetch('/api/data'),
133
+ () => console.log('Request succeeded!'),
134
+ () => console.log('Request failed!')
135
+ );
136
+ ```
137
+
138
+ Only the appropriate callback will be executed:
139
+
140
+ ```typescript
141
+ import promiseTuple from 'promise-tuple';
142
+
143
+ const [error, data] = await promiseTuple(
144
+ someAsyncOperation(),
145
+ () => {
146
+ // This runs on success
147
+ console.log('Operation completed successfully');
148
+ sendAnalytics('success');
149
+ },
150
+ () => {
151
+ // This runs on failure
152
+ console.error('Operation failed');
153
+ sendAnalytics('failure');
154
+ }
155
+ );
156
+ ```
157
+
124
158
  ## API
125
159
 
126
- ### `promiseTuple<R, E>(promise)`
160
+ ### `promiseTuple<R, E>(promise, successCallback?, failureCallback?)`
127
161
 
128
162
  Handles a promise and returns a tuple with error and result.
129
163
 
130
164
  **Parameters:**
131
165
 
132
166
  - `promise: Promise<R>` - The promise to handle
167
+ - `successCallback?: () => void` - Optional callback executed when the promise resolves
168
+ - `failureCallback?: () => void` - Optional callback executed when the promise rejects
133
169
 
134
170
  **Returns:**
135
171
 
@@ -142,8 +178,8 @@ Handles a promise and returns a tuple with error and result.
142
178
 
143
179
  **Behavior:**
144
180
 
145
- - If the promise resolves: returns `[undefined, result]`
146
- - If the promise rejects: returns `[error, undefined]`
181
+ - If the promise resolves: returns `[undefined, result]` and executes `successCallback` if provided
182
+ - If the promise rejects: returns `[error, undefined]` and executes `failureCallback` if provided
147
183
 
148
184
  ## Examples
149
185
 
@@ -186,6 +222,35 @@ async function readConfigFile(path: string) {
186
222
  }
187
223
  ```
188
224
 
225
+ ### With Callbacks for Side Effects
226
+
227
+ ```typescript
228
+ import promiseTuple from 'promise-tuple';
229
+ import db from './database';
230
+
231
+ async function getUserById(id: number) {
232
+ const [error, user] = await promiseTuple(
233
+ db.users.findById(id),
234
+ () => {
235
+ // Track successful database query
236
+ console.log(`User ${id} retrieved successfully`);
237
+ metrics.incrementCounter('db.user.success');
238
+ },
239
+ () => {
240
+ // Track failed database query
241
+ console.error(`Failed to retrieve user ${id}`);
242
+ metrics.incrementCounter('db.user.failure');
243
+ }
244
+ );
245
+
246
+ if (error) {
247
+ return { success: false, message: 'User not found' };
248
+ }
249
+
250
+ return { success: true, user };
251
+ }
252
+ ```
253
+
189
254
  ## License
190
255
 
191
256
  ISC
package/dist/index.cjs CHANGED
@@ -24,8 +24,8 @@ __export(index_exports, {
24
24
  promiseTuple: () => promiseTuple
25
25
  });
26
26
  module.exports = __toCommonJS(index_exports);
27
- async function promiseTuple(promise) {
28
- return promise.then((result) => [void 0, result]).catch((error) => [error, void 0]);
27
+ async function promiseTuple(promise, successCallback, failureCallback) {
28
+ return promise.then((result) => (successCallback?.(), [void 0, result])).catch((error) => (failureCallback?.(), [error, void 0]));
29
29
  }
30
30
  var index_default = promiseTuple;
31
31
  // Annotate the CommonJS export names for ESM import in node:
@@ -1 +1 @@
1
- {"version":3,"sources":["../index.ts"],"sourcesContent":["/**\r\n * Handles a promise and returns a tuple with error and result.\r\n *\r\n * This function wraps a promise and returns a tuple containing either an error or a result,\r\n * similar to Go's error handling pattern. If the promise resolves, the tuple will contain\r\n * `[undefined, result]`. If the promise rejects, the tuple will contain `[error, undefined]`.\r\n *\r\n * @template R - The type of the resolved value. Defaults to `unknown`.\r\n * @template E - The type of the error. Defaults to `unknown`.\r\n * @param promise - The promise to handle.\r\n * @returns A promise that resolves to a tuple containing either an error or a result.\r\n *\r\n * @example\r\n * const [error, data] = await promiseTuple(fetchData());\r\n * if (error) {\r\n * console.error('Error:', error);\r\n * } else {\r\n * console.log('Data:', data);\r\n * }\r\n */\r\nexport async function promiseTuple<R = unknown, E = unknown>(\r\n promise: Promise<R>\r\n): Promise<[E | undefined, R | undefined]> {\r\n return promise\r\n .then((result) => [undefined, result] as [undefined, R])\r\n .catch((error) => [error, undefined] as [E, undefined])\r\n}\r\nexport default promiseTuple\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAoBA,eAAsB,aAClB,SACuC;AACvC,SAAO,QACF,KAAK,CAAC,WAAW,CAAC,QAAW,MAAM,CAAmB,EACtD,MAAM,CAAC,UAAU,CAAC,OAAO,MAAS,CAAmB;AAC9D;AACA,IAAO,gBAAQ;","names":[]}
1
+ {"version":3,"sources":["../index.ts"],"sourcesContent":["/**\r\n * Handles a promise and returns a tuple with error and result.\r\n *\r\n * This function wraps a promise and returns a tuple containing either an error or a result,\r\n * similar to Go's error handling pattern. If the promise resolves, the tuple will contain\r\n * `[undefined, result]`. If the promise rejects, the tuple will contain `[error, undefined]`.\r\n *\r\n * @template R - The type of the resolved value. Defaults to `unknown`.\r\n * @template E - The type of the error. Defaults to `unknown`.\r\n * @param promise - The promise to handle.\r\n * @param successCallback - Optional callback to execute when the promise resolves successfully.\r\n * @param failureCallback - Optional callback to execute when the promise rejects.\r\n * @returns A promise that resolves to a tuple containing either an error or a result.\r\n * On success: `[undefined, result]`\r\n * On failure: `[error, undefined]`\r\n *\r\n * @example\r\n * const [error, data] = await promiseTuple(fetchData());\r\n * if (error) {\r\n * console.error('Error:', error);\r\n * } else {\r\n * console.log('Data:', data);\r\n * }\r\n *\r\n * @example\r\n * const [error, data] = await promiseTuple(\r\n * fetchData(),\r\n * () => console.log('Success!'),\r\n * () => console.log('Failed!')\r\n * );\r\n */\r\nexport async function promiseTuple<R = unknown, E = unknown>(\r\n promise: Promise<R>,\r\n successCallback?: () => void,\r\n failureCallback?: () => void\r\n): Promise<[E | undefined, R | undefined]> {\r\n return promise\r\n .then((result) => (successCallback?.(), [undefined, result] as [undefined, R]))\r\n .catch((error) => (failureCallback?.(), [error, undefined] as [E, undefined]))\r\n}\r\n\r\nexport default promiseTuple\r\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA+BA,eAAsB,aAClB,SACA,iBACA,iBACuC;AACvC,SAAO,QACF,KAAK,CAAC,YAAY,kBAAkB,GAAG,CAAC,QAAW,MAAM,EAAoB,EAC7E,MAAM,CAAC,WAAW,kBAAkB,GAAG,CAAC,OAAO,MAAS,EAAoB;AACrF;AAEA,IAAO,gBAAQ;","names":[]}
package/dist/index.d.cts CHANGED
@@ -8,7 +8,11 @@
8
8
  * @template R - The type of the resolved value. Defaults to `unknown`.
9
9
  * @template E - The type of the error. Defaults to `unknown`.
10
10
  * @param promise - The promise to handle.
11
+ * @param successCallback - Optional callback to execute when the promise resolves successfully.
12
+ * @param failureCallback - Optional callback to execute when the promise rejects.
11
13
  * @returns A promise that resolves to a tuple containing either an error or a result.
14
+ * On success: `[undefined, result]`
15
+ * On failure: `[error, undefined]`
12
16
  *
13
17
  * @example
14
18
  * const [error, data] = await promiseTuple(fetchData());
@@ -17,7 +21,14 @@
17
21
  * } else {
18
22
  * console.log('Data:', data);
19
23
  * }
24
+ *
25
+ * @example
26
+ * const [error, data] = await promiseTuple(
27
+ * fetchData(),
28
+ * () => console.log('Success!'),
29
+ * () => console.log('Failed!')
30
+ * );
20
31
  */
21
- declare function promiseTuple<R = unknown, E = unknown>(promise: Promise<R>): Promise<[E | undefined, R | undefined]>;
32
+ declare function promiseTuple<R = unknown, E = unknown>(promise: Promise<R>, successCallback?: () => void, failureCallback?: () => void): Promise<[E | undefined, R | undefined]>;
22
33
 
23
34
  export { promiseTuple as default, promiseTuple };
package/dist/index.d.ts CHANGED
@@ -8,7 +8,11 @@
8
8
  * @template R - The type of the resolved value. Defaults to `unknown`.
9
9
  * @template E - The type of the error. Defaults to `unknown`.
10
10
  * @param promise - The promise to handle.
11
+ * @param successCallback - Optional callback to execute when the promise resolves successfully.
12
+ * @param failureCallback - Optional callback to execute when the promise rejects.
11
13
  * @returns A promise that resolves to a tuple containing either an error or a result.
14
+ * On success: `[undefined, result]`
15
+ * On failure: `[error, undefined]`
12
16
  *
13
17
  * @example
14
18
  * const [error, data] = await promiseTuple(fetchData());
@@ -17,7 +21,14 @@
17
21
  * } else {
18
22
  * console.log('Data:', data);
19
23
  * }
24
+ *
25
+ * @example
26
+ * const [error, data] = await promiseTuple(
27
+ * fetchData(),
28
+ * () => console.log('Success!'),
29
+ * () => console.log('Failed!')
30
+ * );
20
31
  */
21
- declare function promiseTuple<R = unknown, E = unknown>(promise: Promise<R>): Promise<[E | undefined, R | undefined]>;
32
+ declare function promiseTuple<R = unknown, E = unknown>(promise: Promise<R>, successCallback?: () => void, failureCallback?: () => void): Promise<[E | undefined, R | undefined]>;
22
33
 
23
34
  export { promiseTuple as default, promiseTuple };
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // index.ts
2
- async function promiseTuple(promise) {
3
- return promise.then((result) => [void 0, result]).catch((error) => [error, void 0]);
2
+ async function promiseTuple(promise, successCallback, failureCallback) {
3
+ return promise.then((result) => (successCallback?.(), [void 0, result])).catch((error) => (failureCallback?.(), [error, void 0]));
4
4
  }
5
5
  var index_default = promiseTuple;
6
6
  export {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../index.ts"],"sourcesContent":["/**\r\n * Handles a promise and returns a tuple with error and result.\r\n *\r\n * This function wraps a promise and returns a tuple containing either an error or a result,\r\n * similar to Go's error handling pattern. If the promise resolves, the tuple will contain\r\n * `[undefined, result]`. If the promise rejects, the tuple will contain `[error, undefined]`.\r\n *\r\n * @template R - The type of the resolved value. Defaults to `unknown`.\r\n * @template E - The type of the error. Defaults to `unknown`.\r\n * @param promise - The promise to handle.\r\n * @returns A promise that resolves to a tuple containing either an error or a result.\r\n *\r\n * @example\r\n * const [error, data] = await promiseTuple(fetchData());\r\n * if (error) {\r\n * console.error('Error:', error);\r\n * } else {\r\n * console.log('Data:', data);\r\n * }\r\n */\r\nexport async function promiseTuple<R = unknown, E = unknown>(\r\n promise: Promise<R>\r\n): Promise<[E | undefined, R | undefined]> {\r\n return promise\r\n .then((result) => [undefined, result] as [undefined, R])\r\n .catch((error) => [error, undefined] as [E, undefined])\r\n}\r\nexport default promiseTuple\r\n"],"mappings":";AAoBA,eAAsB,aAClB,SACuC;AACvC,SAAO,QACF,KAAK,CAAC,WAAW,CAAC,QAAW,MAAM,CAAmB,EACtD,MAAM,CAAC,UAAU,CAAC,OAAO,MAAS,CAAmB;AAC9D;AACA,IAAO,gBAAQ;","names":[]}
1
+ {"version":3,"sources":["../index.ts"],"sourcesContent":["/**\r\n * Handles a promise and returns a tuple with error and result.\r\n *\r\n * This function wraps a promise and returns a tuple containing either an error or a result,\r\n * similar to Go's error handling pattern. If the promise resolves, the tuple will contain\r\n * `[undefined, result]`. If the promise rejects, the tuple will contain `[error, undefined]`.\r\n *\r\n * @template R - The type of the resolved value. Defaults to `unknown`.\r\n * @template E - The type of the error. Defaults to `unknown`.\r\n * @param promise - The promise to handle.\r\n * @param successCallback - Optional callback to execute when the promise resolves successfully.\r\n * @param failureCallback - Optional callback to execute when the promise rejects.\r\n * @returns A promise that resolves to a tuple containing either an error or a result.\r\n * On success: `[undefined, result]`\r\n * On failure: `[error, undefined]`\r\n *\r\n * @example\r\n * const [error, data] = await promiseTuple(fetchData());\r\n * if (error) {\r\n * console.error('Error:', error);\r\n * } else {\r\n * console.log('Data:', data);\r\n * }\r\n *\r\n * @example\r\n * const [error, data] = await promiseTuple(\r\n * fetchData(),\r\n * () => console.log('Success!'),\r\n * () => console.log('Failed!')\r\n * );\r\n */\r\nexport async function promiseTuple<R = unknown, E = unknown>(\r\n promise: Promise<R>,\r\n successCallback?: () => void,\r\n failureCallback?: () => void\r\n): Promise<[E | undefined, R | undefined]> {\r\n return promise\r\n .then((result) => (successCallback?.(), [undefined, result] as [undefined, R]))\r\n .catch((error) => (failureCallback?.(), [error, undefined] as [E, undefined]))\r\n}\r\n\r\nexport default promiseTuple\r\n"],"mappings":";AA+BA,eAAsB,aAClB,SACA,iBACA,iBACuC;AACvC,SAAO,QACF,KAAK,CAAC,YAAY,kBAAkB,GAAG,CAAC,QAAW,MAAM,EAAoB,EAC7E,MAAM,CAAC,WAAW,kBAAkB,GAAG,CAAC,OAAO,MAAS,EAAoB;AACrF;AAEA,IAAO,gBAAQ;","names":[]}
package/package.json CHANGED
@@ -1,63 +1,64 @@
1
1
  {
2
- "name": "promise-tuple",
3
- "version": "1.0.0",
4
- "description": "A utility function for handling promises with Go-like error handling pattern",
5
- "main": "./dist/index.cjs",
6
- "module": "./dist/index.js",
7
- "types": "./dist/index.d.ts",
8
- "type": "module",
9
- "exports": {
10
- ".": {
11
- "types": "./dist/index.d.ts",
12
- "require": {
13
- "types": "./dist/index.d.cts",
14
- "default": "./dist/index.cjs"
15
- },
16
- "import": {
17
- "types": "./dist/index.d.ts",
18
- "default": "./dist/index.js"
19
- }
20
- }
21
- },
22
- "sideEffects": false,
23
- "scripts": {
24
- "clean": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\"",
25
- "build": "tsup index.ts",
26
- "test": "tsx index.test.ts",
27
- "prepublishOnly": "npm run clean && npm run build && npm test"
28
- },
29
- "keywords": [
30
- "promise",
31
- "error-handling",
32
- "async",
33
- "utility",
34
- "go-style",
35
- "tuple",
36
- "await",
37
- "typescript"
38
- ],
39
- "author": "Eduardo DONATO <eduardo.donato@gmail.com>",
40
- "license": "ISC",
41
- "repository": {
42
- "type": "git",
43
- "url": "git+https://github.com/ebdonato/promise-tuple.git"
44
- },
45
- "bugs": {
46
- "url": "https://github.com/ebdonato/promise-tuple/issues"
47
- },
48
- "homepage": "https://github.com/ebdonato/promise-tuple#readme",
49
- "engines": {
50
- "node": ">=16"
51
- },
52
- "files": [
53
- "dist",
54
- "README.md",
55
- "LICENSE"
56
- ],
57
- "devDependencies": {
58
- "@types/node": "^20.0.0",
59
- "tsup": "^8.5.1",
60
- "tsx": "^4.21.0",
61
- "typescript": "^5.9.3"
2
+ "name": "promise-tuple",
3
+ "version": "1.1.2",
4
+ "description": "A utility function for handling promises with Go-like error handling pattern",
5
+ "main": "./dist/index.cjs",
6
+ "module": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "type": "module",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "require": {
13
+ "types": "./dist/index.d.cts",
14
+ "default": "./dist/index.cjs"
15
+ },
16
+ "import": {
17
+ "types": "./dist/index.d.ts",
18
+ "default": "./dist/index.js"
19
+ }
62
20
  }
21
+ },
22
+ "sideEffects": false,
23
+ "scripts": {
24
+ "clean": "node -e \"require('fs').rmSync('dist', { recursive: true, force: true })\"",
25
+ "build": "tsup index.ts",
26
+ "test": "vitest run",
27
+ "prepublishOnly": "npm run clean && npm run build && npm test"
28
+ },
29
+ "keywords": [
30
+ "promise",
31
+ "error-handling",
32
+ "async",
33
+ "utility",
34
+ "go-style",
35
+ "tuple",
36
+ "await",
37
+ "typescript"
38
+ ],
39
+ "author": "Eduardo DONATO <eduardo.donato@gmail.com>",
40
+ "license": "ISC",
41
+ "repository": {
42
+ "type": "git",
43
+ "url": "git+https://github.com/ebdonato/promise-tuple.git"
44
+ },
45
+ "bugs": {
46
+ "url": "https://github.com/ebdonato/promise-tuple/issues"
47
+ },
48
+ "homepage": "https://github.com/ebdonato/promise-tuple#readme",
49
+ "engines": {
50
+ "node": ">=16"
51
+ },
52
+ "files": [
53
+ "dist",
54
+ "README.md",
55
+ "LICENSE"
56
+ ],
57
+ "devDependencies": {
58
+ "@types/node": "^20.0.0",
59
+ "tsup": "^8.5.1",
60
+ "tsx": "^4.21.0",
61
+ "typescript": "^5.9.3",
62
+ "vitest": "^4.0.18"
63
+ }
63
64
  }