0
# Promise Utilities
1
2
Conversion tools between callback-based and promise-based function patterns, enabling modern async/await usage with legacy callback APIs and vice versa.
3
4
## Capabilities
5
6
### Promisify Function
7
8
Converts a callback-based function to a promise-based function.
9
10
```javascript { .api }
11
/**
12
* Converts a callback-based function to a promise-based function
13
* @param {Function} original - Function that takes a callback as its last parameter
14
* @returns {Function} Promise-based version of the original function
15
* @throws {TypeError} If original is not a function
16
*/
17
function promisify(original): Function;
18
19
/**
20
* Symbol for custom promisify implementations
21
*/
22
promisify.custom: symbol;
23
```
24
25
The returned function will:
26
- Return a Promise instead of using a callback
27
- Pass all arguments to the original function except the callback
28
- Resolve with the callback's second argument (success value)
29
- Reject with the callback's first argument (error value)
30
31
**Usage Examples:**
32
33
```javascript
34
const util = require('util');
35
const fs = require('fs');
36
37
// Basic promisify
38
const readFileAsync = util.promisify(fs.readFile);
39
40
// Use with async/await
41
async function readConfig() {
42
try {
43
const data = await readFileAsync('config.json', 'utf8');
44
return JSON.parse(data);
45
} catch (error) {
46
console.error('Failed to read config:', error);
47
}
48
}
49
50
// Use with .then()
51
readFileAsync('package.json', 'utf8')
52
.then(data => JSON.parse(data))
53
.then(pkg => console.log(pkg.name))
54
.catch(err => console.error(err));
55
56
// Custom promisify implementation
57
function customReadFile(filename, callback) {
58
// Custom implementation
59
}
60
customReadFile[util.promisify.custom] = function(filename) {
61
return new Promise((resolve, reject) => {
62
// Custom promise logic
63
});
64
};
65
66
const promisifiedCustom = util.promisify(customReadFile);
67
// Will use the custom implementation
68
```
69
70
### Callbackify Function
71
72
Converts a promise-based function to a callback-based function.
73
74
```javascript { .api }
75
/**
76
* Converts a promise-based function to a callback-based function
77
* @param {Function} original - Function that returns a Promise
78
* @returns {Function} Callback-based version of the original function
79
* @throws {TypeError} If original is not a function
80
*/
81
function callbackify(original): Function;
82
```
83
84
The returned function will:
85
- Take a callback as its last parameter
86
- Call the original function with all other arguments
87
- Call the callback with (error, result) based on Promise resolution/rejection
88
- Use `process.nextTick` for proper Node.js callback semantics
89
90
**Usage Examples:**
91
92
```javascript
93
const util = require('util');
94
95
// Promise-based function
96
async function fetchUserData(userId) {
97
const response = await fetch(`/api/users/${userId}`);
98
if (!response.ok) {
99
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
100
}
101
return response.json();
102
}
103
104
// Convert to callback-based
105
const fetchUserDataCallback = util.callbackify(fetchUserData);
106
107
// Use with traditional callback pattern
108
fetchUserDataCallback(123, (err, userData) => {
109
if (err) {
110
console.error('Error fetching user:', err);
111
return;
112
}
113
console.log('User data:', userData);
114
});
115
116
// Another example with rejection handling
117
async function divideAsync(a, b) {
118
if (b === 0) {
119
throw new Error('Division by zero');
120
}
121
return a / b;
122
}
123
124
const divideCallback = util.callbackify(divideAsync);
125
126
divideCallback(10, 2, (err, result) => {
127
if (err) {
128
console.error('Error:', err.message);
129
} else {
130
console.log('Result:', result); // 5
131
}
132
});
133
134
divideCallback(10, 0, (err, result) => {
135
if (err) {
136
console.error('Error:', err.message); // "Division by zero"
137
}
138
});
139
```
140
141
## Promise Requirements
142
143
Both `promisify` and `callbackify` require Promises to be available:
144
- Native Promises (Node.js 4+ or modern browsers)
145
- Polyfill such as es6-promise for older environments
146
147
## Error Handling Patterns
148
149
### Promisify Error Handling
150
- Callback errors (first parameter) become Promise rejections
151
- Callback results (second parameter) become Promise resolutions
152
- Synchronous exceptions in the original function become rejections
153
154
### Callbackify Error Handling
155
- Promise rejections become callback errors (first parameter)
156
- Promise resolutions become callback results (second parameter)
157
- Falsy rejection values are wrapped in Error objects with a `reason` property