0
# Core Promise Creation
1
2
Core functions for creating and managing promises from values, errors, callback functions, and other asynchronous operations.
3
4
## Capabilities
5
6
### Main Q Function
7
8
The primary function for creating promises from any value, including thenables and existing promises.
9
10
```javascript { .api }
11
/**
12
* Creates a promise from a value, thenable, or existing promise
13
* @param value - Any value to convert to a promise
14
* @returns Promise wrapping the value
15
*/
16
function Q(value);
17
```
18
19
**Usage Examples:**
20
21
```javascript
22
const Q = require("q");
23
24
// Create promise from value
25
const valuePromise = Q("Hello");
26
27
// Create promise from thenable
28
const thenable = { then: (resolve) => resolve("World") };
29
const thenablePromise = Q(thenable);
30
31
// Pass through existing promise
32
const existingPromise = Q.resolve("Existing");
33
const passedPromise = Q(existingPromise); // Same promise returned
34
```
35
36
### Deferred Creation
37
38
Creates deferred objects that provide manual control over promise resolution.
39
40
```javascript { .api }
41
/**
42
* Creates a deferred object with promise, resolve, and reject methods
43
* @returns Deferred object with promise property and control methods
44
*/
45
function Q.defer();
46
47
interface Deferred {
48
promise: Promise;
49
resolve(value: any): void;
50
reject(reason: any): void;
51
setEstimate(estimate: number): void;
52
makeNodeResolver(unpack?: boolean): Function;
53
}
54
```
55
56
**Usage Examples:**
57
58
```javascript
59
const Q = require("q");
60
61
// Create and control deferred
62
const deferred = Q.defer();
63
64
setTimeout(() => {
65
if (Math.random() > 0.5) {
66
deferred.resolve("Success!");
67
} else {
68
deferred.reject(new Error("Failed"));
69
}
70
}, 1000);
71
72
deferred.promise
73
.then(value => console.log(value))
74
.catch(error => console.error(error));
75
76
// Node.js callback integration
77
const nodeCallback = deferred.makeNodeResolver();
78
fs.readFile("file.txt", nodeCallback);
79
```
80
81
### Promise Rejection
82
83
Creates promises that are already rejected with the specified error.
84
85
```javascript { .api }
86
/**
87
* Creates a promise rejected with the given error
88
* @param error - Error or reason for rejection
89
* @returns Promise rejected with the error
90
*/
91
function Q.reject(error);
92
```
93
94
**Usage Examples:**
95
96
```javascript
97
const Q = require("q");
98
99
// Create rejected promise
100
const rejected = Q.reject(new Error("Operation failed"));
101
102
// Use in conditional logic
103
function validateInput(input) {
104
if (!input) {
105
return Q.reject(new Error("Input required"));
106
}
107
return Q.resolve(input.toUpperCase());
108
}
109
```
110
111
### Promise Constructor
112
113
Constructor function for creating promises with a resolver function.
114
115
```javascript { .api }
116
/**
117
* Promise constructor that takes a resolver function
118
* @param resolver - Function receiving resolve and reject callbacks
119
* @returns New promise instance
120
*/
121
function Q.Promise(resolver);
122
```
123
124
**Usage Examples:**
125
126
```javascript
127
const Q = require("q");
128
129
// Create promise with constructor
130
const promise = new Q.Promise((resolve, reject) => {
131
const xhr = new XMLHttpRequest();
132
xhr.open("GET", "/api/data");
133
xhr.onload = () => {
134
if (xhr.status === 200) {
135
resolve(JSON.parse(xhr.responseText));
136
} else {
137
reject(new Error(`HTTP ${xhr.status}`));
138
}
139
};
140
xhr.onerror = () => reject(new Error("Network error"));
141
xhr.send();
142
});
143
```
144
145
### Try Function Execution
146
147
Executes a function and returns a promise for its result, catching any synchronous errors.
148
149
```javascript { .api }
150
/**
151
* Calls function and returns promise for result or error
152
* @param callback - Function to execute
153
* @returns Promise for function result or rejection if error thrown
154
*/
155
function Q.try(callback);
156
```
157
158
**Usage Examples:**
159
160
```javascript
161
const Q = require("q");
162
163
// Safe function execution
164
const result = Q.try(() => {
165
return JSON.parse(inputString);
166
});
167
168
result
169
.then(data => console.log("Parsed:", data))
170
.catch(error => console.error("Parse error:", error));
171
172
// With parameters
173
function safeDivide(a, b) {
174
return Q.try(() => {
175
if (b === 0) throw new Error("Division by zero");
176
return a / b;
177
});
178
}
179
```
180
181
### Promise Static Methods
182
183
Static methods available on the Promise constructor for ES6 compatibility.
184
185
```javascript { .api }
186
/**
187
* Static versions of Q functions available on Q.Promise
188
*/
189
Q.Promise.all(promises); // Static version of Q.all
190
Q.Promise.race(promises); // Static version of Q.race
191
Q.Promise.resolve(value); // Static version of Q()
192
Q.Promise.reject(reason); // Static version of Q.reject
193
```
194
195
**Usage Examples:**
196
197
```javascript
198
const Q = require("q");
199
200
// Use static methods
201
const allPromise = Q.Promise.all([
202
Q.resolve(1),
203
Q.resolve(2),
204
Q.resolve(3)
205
]);
206
207
const racePromise = Q.Promise.race([
208
Q.delay("fast", 100),
209
Q.delay("slow", 500)
210
]);
211
```