Objective-C implementation of jQuery-ish promises.
Asynchronous code... blah blah blah... standard interface for... blah blah blah... handling asynchronous actions... blah blah blah... chaining callbacks.
Version | Changes |
---|---|
0.1.2 | then and fail blocks can be undefined now when using When (thanks brennanmke) |
0.1.1 | Fixed issue with EXC_BAD_ACCESS (thanks DanielMSchmidt) |
0.1.0 | Initial release |
Deferred
objects (the controller for the promise) are used change state for promise behavior which triggers callbacksPromise
objects are really just read-onlyDeferred
objects- Add done, fail, and always blocks to a
Deferred
orPromise
object- Add 0 to many done, fail, and always blocks
- Can use "then" method for shortcut to add one done, one fail, and one always block
- Create a
When
object to linkPromise
objects together- The done block executes when all promise object states are "resolved"
- The fail block executes when one promise object state is "rejected"
- The always block executes when all promises are no longer pending
Clone the repository and drop in the .h and .m files from the "Classes" directory into your project.
Promises is available through CocoaPods, to install it simply add the following line to your Podfile:
pod 'Promises', '~> 0.1.1'
Deferred *deferred1 = [Deferred deferred];
[deferred1 addDone:^(id value) {
NSLog(@"WOOT - deferred1 is done - %@", value);
}];
[deferred1 resolveWith:@"Josh is awesome"];
Rejecting a deferred's promise (promise is the same as deferred but doesn't show method for resolving or rejecting.
This would be used if you wanted to return a promise from some method.
Deferred *deferred2 = [Deferred deferred];
Promise *promise = deferred2.promise;
[promise addDone:^(id value) {
NSLog(@"WOOT - deferred2 is done - %@", value);
}];
[promise addFail:^(NSError *error) {
// This fail block's parameter is of type 'id' but I know that it will be an NSError
NSLog(@":( - deferred2 failed - %@", error.domain);
}];
[deferred2 rejectWith:[NSError errorWithDomain:@"Oops" code:0 userInfo:nil]];
Deferred *deferred1 = [Deferred deferred];
Deferred *deferred2 = [Deferred deferred];
[When when:@[deferred1, deferred2] then:^{
NSLog(@"WHEN RESOLVING done called");
} fail:^(NSError *error) {
NSLog(@"WHEN RESOLVING fail called - %@", error.domain);
} always:^{
NSLog(@"WHEN RESOLVING always called");
}];
[deferred1 resolveWith:@"Yay"];
[deferred2 resolveWith:@"Woot"];
Josh Holtz, [email protected], @joshdholtz
Promises is available under the MIT license. See the LICENSE file for more info.