0
# Promise and Observable Utilities
1
2
Ionic Native Core provides comprehensive utilities for creating promises and wrapping plugin methods with Promise/Observable patterns, including special handling for Angular 1 integration and various callback styles.
3
4
## Capabilities
5
6
### Promise Creation
7
8
```typescript { .api }
9
/**
10
* Creates a promise with automatic Angular 1 integration
11
* Falls back to native Promise if Angular 1 $q service is not available
12
* @param callback - Function that receives resolve and reject callbacks
13
* @returns Promise that integrates with Angular 1 digest cycle
14
*/
15
function getPromise<T>(
16
callback: (resolve: Function, reject?: Function) => any
17
): Promise<T>;
18
```
19
20
**Usage Example:**
21
22
```typescript
23
import { getPromise } from "@ionic-native/core";
24
25
const myPromise = getPromise<string>((resolve, reject) => {
26
setTimeout(() => {
27
resolve("Hello World");
28
}, 1000);
29
});
30
31
myPromise.then(result => {
32
console.log(result); // "Hello World"
33
});
34
```
35
36
### Method Wrapping
37
38
```typescript { .api }
39
/**
40
* Wraps plugin methods with Promise/Observable support and error handling
41
* Core utility used by the @Cordova decorator
42
* @param pluginObj - Plugin instance or class
43
* @param methodName - Name of the method to wrap
44
* @param opts - Configuration options for wrapping behavior
45
* @returns Wrapped function that returns Promise or Observable
46
*/
47
function wrap(
48
pluginObj: any,
49
methodName: string,
50
opts?: CordovaOptions
51
): WrapFn;
52
53
type WrapFn = (...args: any[]) => any;
54
55
/**
56
* Wraps plugin instance methods with Promise/Observable support
57
* Used for methods that operate on _objectInstance
58
* @param pluginObj - Plugin object with _objectInstance property
59
* @param methodName - Name of the method to wrap
60
* @param opts - Configuration options for wrapping behavior
61
* @returns Wrapped function that returns Promise or Observable
62
*/
63
function wrapInstance(
64
pluginObj: any,
65
methodName: string,
66
opts?: any
67
): Function;
68
```
69
70
**Usage Examples:**
71
72
```typescript
73
import { wrap, wrapInstance } from "@ionic-native/core";
74
75
// Wrap a standard plugin method
76
const wrappedMethod = wrap(pluginObj, "getData", {
77
successIndex: 0,
78
errorIndex: 1
79
});
80
81
// Usage returns a Promise
82
wrappedMethod(param1, param2).then(result => {
83
console.log("Success:", result);
84
}).catch(error => {
85
console.log("Error:", error);
86
});
87
88
// Wrap an instance method
89
const wrappedInstanceMethod = wrapInstance(pluginObj, "readFile", {
90
observable: true
91
});
92
93
// Usage returns an Observable
94
wrappedInstanceMethod("path/to/file").subscribe(data => {
95
console.log("File data:", data);
96
});
97
```
98
99
### Low-level Plugin Execution
100
101
```typescript { .api }
102
/**
103
* Calls a Cordova plugin method with proper error handling and callback setup
104
* Handles availability checking and argument positioning
105
* @param pluginObj - Plugin instance or class
106
* @param methodName - Method name to call
107
* @param args - Arguments to pass to the method
108
* @param opts - Configuration options
109
* @param resolve - Success callback function
110
* @param reject - Error callback function
111
* @returns Result from plugin method or error object
112
*/
113
function callCordovaPlugin(
114
pluginObj: any,
115
methodName: string,
116
args: any[],
117
opts?: any,
118
resolve?: Function,
119
reject?: Function
120
): any;
121
122
/**
123
* Calls a plugin instance method with proper error handling
124
* Similar to callCordovaPlugin but for _objectInstance methods
125
* @param pluginObj - Plugin object with _objectInstance
126
* @param methodName - Method name to call on the instance
127
* @param args - Arguments to pass to the method
128
* @param opts - Configuration options
129
* @param resolve - Success callback function
130
* @param reject - Error callback function
131
* @returns Result from instance method
132
*/
133
function callInstance(
134
pluginObj: any,
135
methodName: string,
136
args: any[],
137
opts?: any,
138
resolve?: Function,
139
reject?: Function
140
): any;
141
```
142
143
## Advanced Configuration Options
144
145
### Callback Style Handling
146
147
The wrapping utilities support various callback patterns:
148
149
```typescript
150
// Standard callback order (success, error)
151
wrap(pluginObj, "method", {
152
successIndex: 0,
153
errorIndex: 1
154
});
155
156
// Reverse callback order (error, success)
157
wrap(pluginObj, "method", {
158
callbackOrder: "reverse"
159
});
160
161
// Node.js style callbacks (error, result)
162
wrap(pluginObj, "method", {
163
callbackStyle: "node"
164
});
165
166
// Object-style callbacks
167
wrap(pluginObj, "method", {
168
callbackStyle: "object",
169
successName: "onSuccess",
170
errorName: "onError"
171
});
172
```
173
174
### Observable Configuration
175
176
```typescript
177
// Basic Observable
178
wrap(pluginObj, "watchMethod", {
179
observable: true
180
});
181
182
// Observable with cleanup function
183
wrap(pluginObj, "watchMethod", {
184
observable: true,
185
clearFunction: "clearWatch",
186
clearWithArgs: true
187
});
188
189
// Event-based Observable
190
wrap(pluginObj, "eventMethod", {
191
eventObservable: true,
192
event: "deviceready",
193
element: window
194
});
195
```
196
197
### Synchronous Methods
198
199
```typescript
200
// Synchronous method (no Promise wrapping)
201
wrap(pluginObj, "syncMethod", {
202
sync: true
203
});
204
```
205
206
## Internal Utilities
207
208
### Argument Processing
209
210
```typescript { .api }
211
/**
212
* Processes arguments array to insert success/error callbacks at correct positions
213
* @param args - Original arguments array
214
* @param opts - Configuration options specifying callback positions
215
* @param resolve - Success callback to insert
216
* @param reject - Error callback to insert
217
* @returns Modified arguments array with callbacks inserted
218
*/
219
function setIndex(
220
args: any[],
221
opts?: any,
222
resolve?: Function,
223
reject?: Function
224
): any;
225
```
226
227
### Promise Wrapping Variants
228
229
Internal functions used by the core wrapping utilities:
230
231
```typescript { .api }
232
/**
233
* Wraps plugin method calls in promises with error handling
234
* @param pluginObj - Plugin instance
235
* @param methodName - Method to call
236
* @param args - Method arguments
237
* @param opts - Configuration options
238
* @returns Promise that resolves with method result
239
*/
240
function wrapPromise(
241
pluginObj: any,
242
methodName: string,
243
args: any[],
244
opts?: CordovaOptions
245
): Promise<any>;
246
247
/**
248
* Wraps plugin method calls in observables with cleanup support
249
* @param pluginObj - Plugin instance
250
* @param methodName - Method to call
251
* @param args - Method arguments
252
* @param opts - Configuration options
253
* @returns Observable that emits method results
254
*/
255
function wrapObservable(
256
pluginObj: any,
257
methodName: string,
258
args: any[],
259
opts?: any
260
): Observable<any>;
261
262
/**
263
* Wraps plugin methods that return promises natively
264
* @param pluginObj - Plugin instance
265
* @param methodName - Method to call
266
* @param args - Method arguments
267
* @param opts - Configuration options
268
* @returns Promise that resolves with method result
269
*/
270
function wrapOtherPromise(
271
pluginObj: any,
272
methodName: string,
273
args: any[],
274
opts?: any
275
): Promise<any>;
276
277
/**
278
* Creates observable from global event
279
* @param event - Event name to listen for
280
* @param element - Element to attach listener to (defaults to window)
281
* @returns Observable that emits event data
282
*/
283
function wrapEventObservable(event: string, element?: any): Observable<any>;
284
```
285
286
## Angular 1 Integration
287
288
The promise utilities automatically detect and integrate with Angular 1:
289
290
```typescript
291
// Automatically uses Angular's $q service if available
292
const promise = getPromise((resolve, reject) => {
293
// Promise will integrate with Angular's digest cycle
294
resolve(data);
295
});
296
297
// Falls back to native Promise if Angular not available
298
```
299
300
This ensures that promise resolutions trigger Angular's change detection when used in Angular 1 applications.
301
302
## Error Handling Patterns
303
304
The utilities provide consistent error handling:
305
306
```typescript
307
// Promises automatically catch and handle plugin errors
308
wrap(pluginObj, "method").then(result => {
309
// Success
310
}).catch(error => {
311
if (error.error === "cordova_not_available") {
312
// Handle Cordova not available
313
} else if (error.error === "plugin_not_installed") {
314
// Handle plugin not installed
315
}
316
});
317
318
// Observables handle errors in the error callback
319
wrap(pluginObj, "method", { observable: true }).subscribe(
320
result => {
321
// Success
322
},
323
error => {
324
// Handle error
325
}
326
);
327
```