forked from dz-tal/EZiOS7
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PromiseKit.swift
1360 lines (1150 loc) · 39.5 KB
/
PromiseKit.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Dispatch
import Foundation.NSDate
/**
@return A new promise that resolves after the specified duration.
@parameter duration The duration in seconds to wait before this promise is resolve.
For example:
after(1).then {
//…
}
*/
public func after(delay: NSTimeInterval) -> Promise<Void> {
return Promise { fulfill, _ in
let delta = delay * NSTimeInterval(NSEC_PER_SEC)
let when = dispatch_time(DISPATCH_TIME_NOW, Int64(delta))
dispatch_after(when, dispatch_get_global_queue(0, 0)) {
fulfill()
}
}
}
import Foundation.NSError
/**
AnyPromise is a Promise that can be used in Objective-C code
Swift code can only convert Promises to AnyPromises or vice versa.
Libraries that only provide promises will require you to write a
small Swift function that can convert those promises into AnyPromises
as you require them.
To effectively use AnyPromise in Objective-C code you must use `#import`
rather than `@import PromiseKit;`
#import <PromiseKit/PromiseKit.h>
*/
/**
Resolution.Fulfilled takes an Any. When retrieving the Any you cannot
convert it into an AnyObject?. By giving Fulfilled an object that has
an AnyObject? property we never have to cast and everything is fine.
*/
private class Box {
let obj: AnyObject?
init(_ obj: AnyObject?) {
self.obj = obj
}
}
private func box(obj: AnyObject?) -> Resolution {
if let error = obj as? NSError {
unconsume(error)
return .Rejected(error)
} else {
return .Fulfilled(Box(obj))
}
}
private func unbox(resolution: Resolution) -> AnyObject? {
switch resolution {
case .Fulfilled(let box):
return (box as! Box).obj
case .Rejected(let error):
return error
}
}
public typealias AnyPromise = PMKPromise
@objc(PMKAnyPromise) public class PMKPromise: NSObject {
var state: State
/**
@return A new AnyPromise bound to a Promise<T>.
The two promises represent the same task, any changes to either
will instantly reflect on both.
*/
public init<T: AnyObject>(bound: Promise<T>) {
//WARNING copy pasta from below. FIXME how?
var resolve: ((Resolution) -> Void)!
state = UnsealedState(resolver: &resolve)
bound.pipe { resolution in
switch resolution {
case .Fulfilled:
resolve(box(bound.value))
case .Rejected(let error):
resolve(box(error))
}
}
}
public init<T: AnyObject>(bound: Promise<T?>) {
//WARNING copy pasta from above. FIXME how?
var resolve: ((Resolution) -> Void)!
state = UnsealedState(resolver: &resolve)
bound.pipe { resolution in
switch resolution {
case .Fulfilled:
resolve(box(bound.value!))
case .Rejected(let error):
resolve(box(error))
}
}
}
/**
@return A new AnyPromise bound to a Promise<[T]>.
The two promises represent the same task, any changes to either
will instantly reflect on both.
The value is converted to an NSArray so Objective-C can use it.
*/
public init<T: AnyObject>(bound: Promise<[T]>) {
//WARNING copy pasta from above. FIXME how?
var resolve: ((Resolution) -> Void)!
state = UnsealedState(resolver: &resolve)
bound.pipe { resolution in
switch resolution {
case .Fulfilled:
resolve(box(NSArray(array: bound.value!)))
case .Rejected(let error):
resolve(box(error))
}
}
}
/**
@return A new AnyPromise bound to a Promise<[T]>.
The two promises represent the same task, any changes to either
will instantly reflect on both.
The value is converted to an NSArray so Objective-C can use it.
*/
public init<T: AnyObject, U: AnyObject>(bound: Promise<[T:U]>) {
//WARNING copy pasta from above. FIXME how?
var resolve: ((Resolution) -> Void)!
state = UnsealedState(resolver: &resolve)
bound.pipe { resolution in
switch resolution {
case .Fulfilled:
resolve(box(bound.value! as NSDictionary))
case .Rejected(let error):
resolve(box(error))
}
}
}
convenience public init(bound: Promise<Int>) {
self.init(bound: bound.then(on: zalgo) { NSNumber(integer: $0) })
}
convenience public init(bound: Promise<Void>) {
self.init(bound: bound.then(on: zalgo) { _ -> AnyObject? in return nil })
}
@objc init(@noescape bridge: ((AnyObject?) -> Void) -> Void) {
var resolve: ((Resolution) -> Void)!
state = UnsealedState(resolver: &resolve)
bridge { result in
func preresolve(obj: AnyObject?) {
resolve(box(obj))
}
if let next = result as? AnyPromise {
next.pipe(preresolve)
} else {
preresolve(result)
}
}
}
@objc func pipe(body: (AnyObject?) -> Void) {
state.get { seal in
func prebody(resolution: Resolution) {
body(unbox(resolution))
}
switch seal {
case .Pending(let handlers):
handlers.append(prebody)
case .Resolved(let resolution):
prebody(resolution)
}
}
}
@objc var __value: AnyObject? {
if let resolution = state.get() {
return unbox(resolution)
} else {
return nil
}
}
/**
A promise starts pending and eventually resolves.
@return True if the promise has not yet resolved.
*/
@objc public var pending: Bool {
return state.get() == nil
}
/**
A promise starts pending and eventually resolves.
@return True if the promise has resolved.
*/
@objc public var resolved: Bool {
return !pending
}
/**
A promise starts pending and eventually resolves.
A fulfilled promise is resolved and succeeded.
@return True if the promise was fulfilled.
*/
@objc public var fulfilled: Bool {
switch state.get() {
case .Some(.Fulfilled):
return true
default:
return false
}
}
/**
A promise starts pending and eventually resolves.
A rejected promise is resolved and failed.
@return True if the promise was rejected.
*/
@objc public var rejected: Bool {
switch state.get() {
case .Some(.Rejected):
return true
default:
return false
}
}
// because you can’t access top-level Swift functions in objc
@objc class func setUnhandledErrorHandler(body: (NSError) -> Void) -> (NSError) -> Void {
let oldHandler = PMKUnhandledErrorHandler
PMKUnhandledErrorHandler = body
return oldHandler
}
/**
Continue a Promise<T> chain from an AnyPromise.
*/
public func then<T>(on q: dispatch_queue_t = dispatch_get_main_queue(), body: (AnyObject?) -> T) -> Promise<T> {
return Promise { fulfill, reject in
pipe { object in
if let error = object as? NSError {
reject(error)
} else {
let value: AnyObject? = self.valueForKey("value")
contain_zalgo(q) {
fulfill(body(value))
}
}
}
}
}
/**
Continue a Promise<T> chain from an AnyPromise.
*/
public func then(on q: dispatch_queue_t = dispatch_get_main_queue(), body: (AnyObject?) -> AnyPromise) -> Promise<AnyObject?> {
return Promise { fulfill, reject in
pipe { object in
if let error = object as? NSError {
reject(error)
} else {
contain_zalgo(q) {
body(object).pipe { object in
if let error = object as? NSError {
reject(error)
} else {
fulfill(object)
}
}
}
}
}
}
}
/**
Continue a Promise<T> chain from an AnyPromise.
*/
public func then<T>(on q: dispatch_queue_t = dispatch_get_main_queue(), body: (AnyObject?) -> Promise<T>) -> Promise<T> {
return Promise(passthru: { resolve in
pipe { object in
if let error = object as? NSError {
resolve(.Rejected(error))
} else {
contain_zalgo(q) {
body(object).pipe(resolve)
}
}
}
})
}
}
extension AnyPromise: DebugPrintable {
override public var debugDescription: String {
return "AnyPromise: \(state)"
}
}
import Dispatch
import Foundation.NSError
public func dispatch_promise<T>(on queue: dispatch_queue_t = dispatch_get_global_queue(0, 0), body: () -> T) -> Promise<T> {
return Promise { sealant in
contain_zalgo(queue) {
sealant.resolve(body())
}
}
}
// TODO Swift 1.2 thinks that usage of the following two is ambiguous
//public func dispatch_promise<T>(on queue: dispatch_queue_t = dispatch_get_global_queue(0, 0), body: () -> Promise<T>) -> Promise<T> {
// return Promise { sealant in
// contain_zalgo(queue) {
// body().pipe(sealant.handler)
// }
// }
//}
public func dispatch_promise<T>(on: dispatch_queue_t = dispatch_get_global_queue(0, 0), body: () -> (T!, NSError!)) -> Promise<T> {
return Promise{ (sealant: Sealant) -> Void in
contain_zalgo(on) {
let (a, b) = body()
sealant.resolve(a, b)
}
}
}
import Dispatch
import Foundation.NSError
/**
The unhandled error handler.
If a promise is rejected and no catch handler is called in its chain, the
provided handler is called. The default handler logs the error.
PMKUnhandledErrorHandler = { error in
println("Unhandled error: \(error)")
}
@warning *Important* The handler is executed on an undefined queue.
@warning *Important* Don’t use promises in your handler, or you risk an
infinite error loop.
@return The previous unhandled error handler.
*/
public var PMKUnhandledErrorHandler = { (error: NSError) -> Void in
dispatch_async(dispatch_get_main_queue()) {
if !error.cancelled {
NSLog("PromiseKit: Unhandled error: %@", error)
}
}
}
private class Consumable: NSObject {
let parentError: NSError
var consumed: Bool = false
deinit {
if !consumed {
PMKUnhandledErrorHandler(parentError)
}
}
init(parent: NSError) {
// we take a copy to avoid a retain cycle. A weak ref
// is no good because then the error is deallocated
// before we can call PMKUnhandledErrorHandler()
parentError = parent.copy() as! NSError
}
}
private var handle: UInt8 = 0
func consume(error: NSError) {
// The association could be nil if the objc_setAssociatedObject
// has taken a *really* long time. Or perhaps the user has
// overused `zalgo`. Thus we ignore it. This is an unlikely edge
// case and the unhandled-error feature is not mission-critical.
if let pmke = objc_getAssociatedObject(error, &handle) as? Consumable {
pmke.consumed = true
}
}
extension AnyPromise {
// objc can't see Swift top-level function :(
//TODO move this and the one in AnyPromise to a compat something
@objc class func __consume(error: NSError) {
consume(error)
}
}
func unconsume(error: NSError) {
if let pmke = objc_getAssociatedObject(error, &handle) as! Consumable? {
pmke.consumed = false
} else {
// this is how we know when the error is deallocated
// because we will be deallocated at the same time
objc_setAssociatedObject(error, &handle, Consumable(parent: error), objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN))
}
}
private struct ErrorPair: Hashable {
let domain: String
let code: Int
init(_ d: String, _ c: Int) {
domain = d; code = c
}
var hashValue: Int {
return "\(domain):\(code)".hashValue
}
}
private func ==(lhs: ErrorPair, rhs: ErrorPair) -> Bool {
return lhs.domain == rhs.domain && lhs.code == rhs.code
}
private var cancelledErrorIdentifiers = Set([
ErrorPair(PMKErrorDomain, PMKOperationCancelled),
ErrorPair(NSURLErrorDomain, NSURLErrorCancelled)
])
extension NSError {
public class func cancelledError() -> NSError {
let info: [NSObject: AnyObject] = [NSLocalizedDescriptionKey: "The operation was cancelled"]
return NSError(domain: PMKErrorDomain, code: PMKOperationCancelled, userInfo: info)
}
/**
You may only call this on the main thread.
*/
public class func registerCancelledErrorDomain(domain: String, code: Int) {
cancelledErrorIdentifiers.insert(ErrorPair(domain, code))
}
/**
You may only call this on the main thread.
*/
public var cancelled: Bool {
return cancelledErrorIdentifiers.contains(ErrorPair(domain, code))
}
}
import Foundation
private func b0rkedEmptyRailsResponse() -> NSData {
return NSData(bytes: " ", length: 1)
}
public func NSJSONFromData(data: NSData) -> Promise<NSArray> {
if data == b0rkedEmptyRailsResponse() {
return Promise(NSArray())
} else {
return NSJSONFromDataT(data)
}
}
public func NSJSONFromData(data: NSData) -> Promise<NSDictionary> {
if data == b0rkedEmptyRailsResponse() {
return Promise(NSDictionary())
} else {
return NSJSONFromDataT(data)
}
}
private func NSJSONFromDataT<T>(data: NSData) -> Promise<T> {
var error: NSError?
let json: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options:nil, error:&error)
if let cast = json as? T {
return Promise(cast)
} else if let error = error {
// NSJSONSerialization gives awful errors, so we wrap it
let debug = error.userInfo!["NSDebugDescription"] as? String
let description = "The server’s JSON response could not be decoded. (\(debug))"
return Promise(NSError(domain: PMKErrorDomain, code: PMKJSONError, userInfo: [
NSLocalizedDescriptionKey: "There was an error decoding the server’s JSON response.",
NSUnderlyingErrorKey: error
]))
} else {
var info = [NSObject: AnyObject]()
info[NSLocalizedDescriptionKey] = "The server returned JSON in an unexpected arrangement"
info[PMKJSONErrorJSONObjectKey] = json
return Promise(NSError(domain: PMKErrorDomain, code: PMKJSONError, userInfo: info))
}
}
import Foundation.NSError
extension Promise {
/**
@return The error with which this promise was rejected; nil if this promise is not rejected.
*/
public var error: NSError? {
switch state.get() {
case .None:
return nil
case .Some(.Fulfilled):
return nil
case .Some(.Rejected(let error)):
return error
}
}
/**
@return `YES` if the promise has not yet resolved.
*/
public var pending: Bool {
return state.get() == nil
}
/**
@return `YES` if the promise has resolved.
*/
public var resolved: Bool {
return !pending
}
/**
@return `YES` if the promise was fulfilled.
*/
public var fulfilled: Bool {
return value != nil
}
/**
@return `YES` if the promise was rejected.
*/
public var rejected: Bool {
return error != nil
}
}
import Foundation.NSError
public let PMKOperationQueue = NSOperationQueue()
public enum CatchPolicy {
case AllErrors
case AllErrorsExceptCancellation
}
/**
A promise represents the future value of a task.
To obtain the value of a promise we call `then`.
Promises are chainable: `then` returns a promise, you can call `then` on
that promise, which returns a promise, you can call `then` on that
promise, et cetera.
0.2.4.6.8.0.2.4.6.8.0.2.4.6.8.0.2.4.6.8.0.2.4.6.8.0.2.4.6.8.0.2.4.6.8.0.2
Promises start in a pending state and *resolve* with a value to become
*fulfilled* or with an `NSError` to become rejected.
@see [PromiseKit `then` Guide](http://promisekit.org/then/)
@see [PromiseKit Chaining Guide](http://promisekit.org/chaining/)
*/
public class Promise<T> {
let state: State
/**
Create a new pending promise.
Use this method when wrapping asynchronous systems that do *not* use
promises so that they can be involved in promise chains.
Don’t use this method if you already have promises! Instead, just return
your promise!
The closure you pass is executed immediately on the calling thread.
func fetchKitten() -> Promise<UIImage> {
return Promise { fulfill, reject in
KittenFetcher.fetchWithCompletionBlock({ img, err in
if err == nil {
fulfill(img)
} else {
reject(err)
}
})
}
}
@param resolvers The provided closure is called immediately. Inside,
execute your asynchronous system, calling fulfill if it suceeds and
reject for any errors.
@return A new promise.
@warning *Note* If you are wrapping a delegate-based system, we recommend
to use instead: defer
@see http://promisekit.org/sealing-your-own-promises/
@see http://promisekit.org/wrapping-delegation/
*/
public convenience init(@noescape resolvers: (fulfill: (T) -> Void, reject: (NSError) -> Void) -> Void) {
self.init(sealant: { sealant in
resolvers(fulfill: sealant.resolve, reject: sealant.resolve)
})
}
/**
Create a new pending promise.
This initializer is convenient when wrapping asynchronous systems that
use common patterns. For example:
func fetchKitten() -> Promise<UIImage> {
return Promise { sealant in
KittenFetcher.fetchWithCompletionBlock(sealant.resolve)
}
}
@see Sealant
@see init(resolvers:)
*/
public init(@noescape sealant: (Sealant<T>) -> Void) {
var resolve: ((Resolution) -> Void)!
state = UnsealedState(resolver: &resolve)
sealant(Sealant(body: resolve))
}
/**
Create a new fulfilled promise.
*/
public init(_ value: T) {
state = SealedState(resolution: .Fulfilled(value))
}
/**
Create a new rejected promise.
*/
public init(_ error: NSError) {
unconsume(error)
state = SealedState(resolution: .Rejected(error))
}
/**
I’d prefer this to be the designated initializer, but then there would be no
public designated unsealed initializer! Making this convenience would be
inefficient. Not very inefficient, but still it seems distasteful to me.
*/
init(@noescape passthru: ((Resolution) -> Void) -> Void) {
var resolve: ((Resolution) -> Void)!
state = UnsealedState(resolver: &resolve)
passthru(resolve)
}
/**
defer is convenient for wrapping delegates or larger asynchronous systems.
class Foo: BarDelegate {
let (promise, fulfill, reject) = Promise<Int>.defer()
func barDidFinishWithResult(result: Int) {
fulfill(result)
}
func barDidError(error: NSError) {
reject(error)
}
}
@return A tuple consisting of:
1) A promise
2) A function that fulfills that promise
3) A function that rejects that promise
*/
public class func defer() -> (promise: Promise, fulfill: (T) -> Void, reject: (NSError) -> Void) {
var sealant: Sealant<T>!
let promise = Promise { sealant = $0 }
return (promise, sealant.resolve, sealant.resolve)
}
func pipe(body: (Resolution) -> Void) {
state.get { seal in
switch seal {
case .Pending(let handlers):
handlers.append(body)
case .Resolved(let resolution):
body(resolution)
}
}
}
private convenience init<U>(when: Promise<U>, body: (Resolution, (Resolution) -> Void) -> Void) {
self.init(passthru: { resolve in
when.pipe{ body($0, resolve) }
})
}
/**
The provided block is executed when this Promise is resolved.
If you provide a block that takes a parameter, the value of the receiver will be passed as that parameter.
@param on The queue on which body should be executed.
@param body The closure that is executed when this Promise is fulfilled.
[NSURLConnection GET:url].then(^(NSData *data){
// do something with data
});
@return A new promise that is resolved with the value returned from the provided closure. For example:
[NSURLConnection GET:url].then(^(NSData *data){
return data.length;
}).then(^(NSNumber *number){
//…
});
@see thenInBackground
*/
public func then<U>(on q: dispatch_queue_t = dispatch_get_main_queue(), _ body: (T) -> U) -> Promise<U> {
return Promise<U>(when: self) { resolution, resolve in
switch resolution {
case .Rejected:
resolve(resolution)
case .Fulfilled(let value):
contain_zalgo(q) {
resolve(.Fulfilled(body(value as! T)))
}
}
}
}
public func then<U>(on q: dispatch_queue_t = dispatch_get_main_queue(), _ body: (T) -> Promise<U>) -> Promise<U> {
return Promise<U>(when: self) { resolution, resolve in
switch resolution {
case .Rejected:
resolve(resolution)
case .Fulfilled(let value):
contain_zalgo(q) {
body(value as! T).pipe(resolve)
}
}
}
}
public func then(on q: dispatch_queue_t = dispatch_get_main_queue(), body: (T) -> AnyPromise) -> Promise<AnyObject?> {
return Promise<AnyObject?>(when: self) { resolution, resolve in
switch resolution {
case .Rejected:
resolve(resolution)
case .Fulfilled(let value):
contain_zalgo(q) {
let anypromise = body(value as! T)
anypromise.pipe { obj in
if let error = obj as? NSError {
resolve(.Rejected(error))
} else {
// possibly the value of this promise is a PMKManifold, if so
// calling the objc `value` method will return the first item.
let obj: AnyObject? = anypromise.valueForKey("value")
resolve(.Fulfilled(obj))
}
}
}
}
}
}
/**
The provided closure is executed on the default background queue when this Promise is fulfilled.
This method is provided as a convenience for `then`.
@see then
*/
public func thenInBackground<U>(body: (T) -> U) -> Promise<U> {
return then(on: dispatch_get_global_queue(0, 0), body)
}
public func thenInBackground<U>(body: (T) -> Promise<U>) -> Promise<U> {
return then(on: dispatch_get_global_queue(0, 0), body)
}
/**
The provided closure is executed when this Promise is rejected.
Rejecting a promise cascades: rejecting all subsequent promises (unless
recover is invoked) thus you will typically place your catch at the end
of a chain. Often utility promises will not have a catch, instead
delegating the error handling to the caller.
The provided closure always runs on the main queue.
@param policy The default policy does not execute your handler for
cancellation errors. See registerCancellationError for more
documentation.
@param body The handler to execute when this Promise is rejected.
@see registerCancellationError
*/
public func catch(policy: CatchPolicy = .AllErrorsExceptCancellation, _ body: (NSError) -> Void) {
pipe { resolution in
switch resolution {
case .Fulfilled:
break
case .Rejected(let error):
dispatch_async(dispatch_get_main_queue()) {
if policy == .AllErrors || !error.cancelled {
consume(error)
body(error)
}
}
}
}
}
/**
The provided closure is executed when this Promise is rejected giving you
an opportunity to recover from the error and continue the promise chain.
*/
public func recover(on q: dispatch_queue_t = dispatch_get_main_queue(), _ body: (NSError) -> Promise<T>) -> Promise<T> {
return Promise(when: self) { resolution, resolve in
switch resolution {
case .Rejected(let error):
contain_zalgo(q) {
consume(error)
body(error).pipe(resolve)
}
case .Fulfilled:
resolve(resolution)
}
}
}
/**
The provided closure is executed when this Promise is resolved.
@param on The queue on which body should be executed.
@param body The closure that is executed when this Promise is resolved.
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
somePromise().then {
//…
}.finally {
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
}
*/
public func finally(on q: dispatch_queue_t = dispatch_get_main_queue(), _ body: () -> Void) -> Promise<T> {
return Promise(when: self) { resolution, resolve in
contain_zalgo(q) {
body()
resolve(resolution)
}
}
}
/**
@return The value with which this promise was fulfilled or nil if this
promise is not fulfilled.
*/
public var value: T? {
switch state.get() {
case .None:
return nil
case .Some(.Fulfilled(let value)):
return (value as! T)
case .Some(.Rejected):
return nil
}
}
}
/**
Zalgo is dangerous.
Pass as the `on` parameter for a `then`. Causes the handler to be executed
as soon as it is resolved. That means it will be executed on the queue it
is resolved. This means you cannot predict the queue.
In the case that the promise is already resolved the handler will be
executed immediately.
zalgo is provided for libraries providing promises that have good tests
that prove unleashing zalgo is safe. You can also use it in your
application code in situations where performance is critical, but be
careful: read the essay at the provided link to understand the risks.
@see http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony
*/
public let zalgo: dispatch_queue_t = dispatch_queue_create("Zalgo", nil)
/**
Waldo is dangerous.
Waldo is zalgo, unless the current queue is the main thread, in which case
we dispatch to the default background queue.
If your block is likely to take more than a few milliseconds to execute,
then you should use waldo: 60fps means the main thread cannot hang longer
than 17 milliseconds. Don’t contribute to UI lag.
Conversely if your then block is trivial, use zalgo: GCD is not free and
for whatever reason you may already be on the main thread so just do what
you are doing quickly and pass on execution.
It is considered good practice for asynchronous APIs to complete onto the
main thread. Apple do not always honor this, nor do other developers.
However, they *should*. In that respect waldo is a good choice if your
then is going to take a while and doesn’t interact with the UI.
Please note (again) that generally you should not use zalgo or waldo. The
performance gains are neglible and we provide these functions only out of
a misguided sense that library code should be as optimized as possible.
If you use zalgo or waldo without tests proving their correctness you may
unwillingly introduce horrendous, near-impossible-to-trace bugs.
@see zalgo
*/
public let waldo: dispatch_queue_t = dispatch_queue_create("Waldo", nil)
func contain_zalgo(q: dispatch_queue_t, block: () -> Void) {
if q === zalgo {
block()
} else if q === waldo {
if NSThread.isMainThread() {
dispatch_async(dispatch_get_global_queue(0, 0), block)
} else {
block()
}
} else {
dispatch_async(q, block)
}
}
extension Promise {
/**
Creates a rejected Promise with `PMKErrorDomain` and a specified localizedDescription and error code.
*/
public convenience init(error: String, code: Int = PMKUnexpectedError) {
let error = NSError(domain: "PMKErrorDomain", code: code, userInfo: [NSLocalizedDescriptionKey: error])
self.init(error)
}
/**
Promise<Any> is more flexible, and often needed. However Swift won't cast
<T> to <Any> directly. Once that is possible we will deprecate this
function.
*/
public func asAny() -> Promise<Any> {
return Promise<Any>(passthru: pipe)
}
/**
Promise<AnyObject> is more flexible, and often needed. However Swift won't
cast <T> to <AnyObject> directly. Once that is possible we will deprecate
this function.
*/
public func asAnyObject() -> Promise<AnyObject> {
return Promise<AnyObject>(passthru: pipe)
}
/**
Swift (1.2) seems to be much less fussy about Void promises.
*/
public func asVoid() -> Promise<Void> {
return then(on: zalgo) { _ in return }
}
}
extension Promise: DebugPrintable {
public var debugDescription: String {
return "Promise: \(state)"