0
# Promise Operations
1
2
The core promise implementation providing asynchronous operations and lazy evaluation. Promises can represent both future values and deferred computations, allowing for complex chaining and composition patterns.
3
4
## Capabilities
5
6
### Promise Creation
7
8
Create promise objects with optional functions, arguments, and error handling.
9
10
```python { .api }
11
class promise:
12
def __init__(self, fun=None, args=None, kwargs=None, callback=None, on_error=None, weak=False, ignore_result=False):
13
"""
14
Create a new promise.
15
16
Parameters:
17
- fun: callable, function to execute when promise is fulfilled
18
- args: tuple, positional arguments for the function
19
- kwargs: dict, keyword arguments for the function
20
- callback: promise or callable, callback to chain immediately
21
- on_error: promise or callable, error handler for exceptions
22
- weak: bool, use weak references for the function (prevents memory leaks)
23
- ignore_result: bool, ignore function return value (performance optimization)
24
"""
25
```
26
27
**Usage Examples:**
28
29
```python
30
from vine import promise
31
32
# Empty promise to be fulfilled later
33
p = promise()
34
35
# Promise with function and arguments
36
p = promise(print, args=("Hello, World!",))
37
38
# Promise that ignores return value (optimization)
39
p = promise(some_function, ignore_result=True)
40
41
# Promise with error handling
42
p = promise(risky_function, on_error=error_handler)
43
```
44
45
### Promise Fulfillment
46
47
Execute the promise with arguments, triggering callback chain.
48
49
```python { .api }
50
def __call__(self, *args, **kwargs):
51
"""
52
Fulfill the promise by executing its function with provided arguments.
53
54
Parameters:
55
- *args: additional positional arguments
56
- **kwargs: additional keyword arguments
57
58
Returns:
59
Return value of the promise function, or None if cancelled/failed
60
"""
61
```
62
63
**Usage Examples:**
64
65
```python
66
# Fulfill empty promise with value
67
p = promise()
68
p.then(lambda x: print(f"Got: {x}"))
69
p(42) # Prints: Got: 42
70
71
# Fulfill promise with function
72
p = promise(lambda x, y: x + y, args=(10,))
73
result = p(20) # Returns 30
74
```
75
76
### Promise Chaining
77
78
Chain promises together using the `.then()` method for sequential operations.
79
80
```python { .api }
81
def then(self, callback, on_error=None):
82
"""
83
Chain a callback to execute when promise is fulfilled.
84
85
Parameters:
86
- callback: callable or promise, function to execute with promise result
87
- on_error: callable or promise, error handler for this callback
88
89
Returns:
90
The callback promise for further chaining
91
"""
92
```
93
94
**Usage Examples:**
95
96
```python
97
# Simple chaining
98
p1 = promise(lambda x: x * 2)
99
p2 = p1.then(lambda x: x + 10)
100
p3 = p2.then(lambda x: print(f"Final: {x}"))
101
102
p1(5) # Prints: Final: 20
103
104
# Chain with error handling
105
p = promise(risky_operation)
106
p.then(
107
success_handler,
108
on_error=lambda exc: print(f"Error: {exc}")
109
)
110
```
111
112
### Error Handling
113
114
Handle exceptions and propagate errors through promise chains.
115
116
```python { .api }
117
def throw(self, exc=None, tb=None, propagate=True):
118
"""
119
Throw an exception through the promise chain.
120
121
Parameters:
122
- exc: Exception, exception to throw (uses current exception if None)
123
- tb: traceback, traceback object for exception
124
- propagate: bool, whether to re-raise if no error handler
125
"""
126
127
def throw1(self, exc=None):
128
"""
129
Throw exception to this promise only (no propagation).
130
131
Parameters:
132
- exc: Exception, exception to throw (uses current exception if None)
133
"""
134
```
135
136
**Usage Examples:**
137
138
```python
139
# Handle errors in promise chain
140
p = promise()
141
p.then(
142
lambda x: x / 0, # Will cause error
143
on_error=lambda exc: print(f"Caught: {exc}")
144
)
145
p(10)
146
147
# Manually throw exception
148
p = promise()
149
p.then(lambda x: print("Success"))
150
p.throw(ValueError("Something went wrong"))
151
```
152
153
### Promise Cancellation
154
155
Cancel promises and stop execution of callback chains.
156
157
```python { .api }
158
def cancel(self):
159
"""
160
Cancel the promise and all pending callbacks.
161
162
Cancellation propagates through the entire callback chain,
163
stopping execution and cleaning up resources.
164
"""
165
```
166
167
**Usage Examples:**
168
169
```python
170
# Cancel individual promise
171
p = promise()
172
p.then(lambda x: print("This won't run"))
173
p.cancel()
174
p(42) # Nothing happens
175
176
# Cancellation propagates through chains
177
p1 = promise()
178
p2 = p1.then(lambda x: x * 2)
179
p3 = p2.then(lambda x: print(x))
180
181
p1.cancel() # Cancels entire chain
182
```
183
184
### Promise Properties
185
186
Access promise state and values.
187
188
```python { .api }
189
@property
190
def ready(self) -> bool:
191
"""True when promise has been fulfilled (successfully or with error)."""
192
193
@property
194
def failed(self) -> bool:
195
"""True when promise failed with an exception."""
196
197
@property
198
def cancelled(self) -> bool:
199
"""True when promise has been cancelled."""
200
201
@property
202
def value(self) -> tuple:
203
"""
204
Promise fulfillment value as (args, kwargs) tuple.
205
Only available when ready=True and failed=False.
206
"""
207
208
@property
209
def reason(self) -> Exception:
210
"""
211
Exception that caused promise failure.
212
Only available when failed=True.
213
"""
214
215
@property
216
def listeners(self) -> list:
217
"""List of pending callback promises."""
218
```
219
220
**Usage Examples:**
221
222
```python
223
p = promise(lambda x: x * 2)
224
225
print(p.ready) # False
226
print(p.failed) # False
227
print(p.cancelled) # False
228
229
p(10)
230
231
print(p.ready) # True
232
print(p.value) # ((20,), {})
233
print(p.failed) # False
234
```
235
236
## Advanced Usage
237
238
### Weak References
239
240
Use weak references to prevent memory leaks in long-lived promise chains:
241
242
```python
243
# Weak reference prevents circular references
244
method_promise = promise(obj.method, weak=True)
245
```
246
247
### Performance Optimization
248
249
For promises that don't need return values:
250
251
```python
252
# Ignore return value for better performance
253
logging_promise = promise(logger.info, ignore_result=True)
254
```
255
256
### Complex Chaining
257
258
Promises can be chained in complex patterns:
259
260
```python
261
# Conditional chaining
262
def process_data(data):
263
p = promise(validate_data, args=(data,))
264
265
# Chain different operations based on validation
266
p.then(lambda valid_data:
267
transform_data(valid_data) if valid_data else None
268
).then(lambda result:
269
save_result(result) if result else None
270
)
271
272
return p
273
```