Q 0.9.3

Q 0.9.3

TestsTested
LangLanguage Obj-CObjective C
License Apache-2.0
ReleasedLast Release May 2018

Maintained by Julian Goacher.



Q 0.9.3

  • By
  • Julian Goacher

Q-ios

An asynchronous promise implementation for iOS.

Inspired by the Q asynchronous promise library for node, this library provides a partial implementation of the Promises/A+ spec.

Installation

Install using CocoaPods:

pod 'Q'

Usage

Create a new promise:

#import "Q.h"
...
QPromise *promise = [QPromise new];

Later, resolve the promise with a result value:

id value = @"something";
[promise resolve:value];

Or reject the promise with an error:

NSError *error = [self raiseError];
[promise reject:error];

Promise continuations can be supplied using blocks:

QPromise *promise = [self asynchronousOp];
promise.then((id)^(id result) {
  // Use result.
})
.fail(^(id error) {
  // Handle error.
});

Promises can be chained using blocks:

QPromise *promise = [QPromise new];
promise.then((id)(^id result) {
    return [QPromise resolve:@"a result!"];
});

or by resolving a promise with a promise:

QPromise *promiseA = [QPromise new];
QPromise *promiseB = [QPromise new];

/// ...stuff...

promiseA.resolve( promiseB );

Create a resolved promise:

QPromise *resolved = [QPromise resolve:@"a result!"];

Or create a rejected promise:

QPromise *rejected = [QPromise reject:@"obsolete"];

Multiple promises

Multiple asynchronous operations can be resolved in one go using the all: method:

QPromise *promise1 = [self httpGet:url1];
QPromise *promise2 = [self httpGet:url2];
QPromise *promise3 = [self httpGet:url3];
NSArray *pending = @[ promise1, promise2, promise3 ];

[QPromise all:pending]
.then((id)^(NSArray *results) {
    id result1 = results[1];
    id result2 = results[2];
    id result3 = results[3];
    // Process results...
})
.fail(^(id error) {
    // Process error...
});

The then block will be passed an array containing the result returned by each corresponding promise in the pending array. If any asynchronous operation fails and its promise rejected then the first error is passed to the fail block.

Gotchas

A then block must return a value. If you fail to do this, then XCode will not generate an error or warning when the code is compiled, but the code will crash with a BAD_ACCESS exception when the block returns:

promise.then((id)^(id result) {
  // No return statement here, code will crash!
});

This can be a particularly easy mistake to make when a then block is the final step in a calculation and doesn't generate any particular result; in these cases, the block should return nil.

Status

This project is currently released as beta code; however, it is fairly well tested and has been used in a number of production projects.