iOS 中的 promise 模式

标签(空格分隔): Promise PromiseKit 异步 Bolts-iOS


1、概述

  异步编程 App 开发中用得非常频繁,但异步请求后的操作却比较麻烦。Promise 就是解决这一问题的编程模型。其适用于 延迟(deferred) 计算和 异步(asynchronous) 计算。一个 Promise 对象代表着一个还未完成,但预期将来会完成的操作。它并非要替代 GCD 和 NSOperation,而是与它们一起合作。

2、历史

  Promise 的出现已经很久了,这个术语首页在 C++ 中出现,之后被用在 E 语言中。2009年,提出 CommonJS 的 Promises/A 规范。它能在今天变得如此引人注目,则得归功于 jQuery 框架了,随着 jQuery 1.5 版本中的 Promises 实现,越来越多的人喜欢上它了。

3、介绍

  Promise 模式,可以简单理解为延后执行。Promise,中文意思为发誓(承诺),既然都发誓了,也就一定会有某些行为的发生。Promise 对象是一个返回值的代理,这个返回值在promise对象创建时未必已知。它允许你为异步操作的成功或失败指定处理方法。 这使得异步方法可以像同步方法那样返回值:异步方法会返回一个包含了原返回值的 promise 对象来替代原返回值。

  Promise对象有以下几种状态:

  • pending: 初始状态, 非 fulfilled 或 rejected.
  • fulfilled: 成功的操作.
  • rejected: 失败的操作.

      pending状态的promise对象既可转换为带着一个成功值的 fulfilled 状态,也可变为带着一个 error 信息的 rejected 状态。当状态发生转换时,promise.then 绑定的方法就会被调用。(当绑定方法时,如果 promise 对象已经处于 fulfilledrejected 状态,那么相应的方法将会被立刻调用, 所以在异步操作的完成情况和它的绑定方法之间不存在竞争条件。)

      因为 Promise.then 方法会返回 promises 对象, 所以可以链式调用,待会咱们就会看到的。
      
    状态转换

4、PromiseKit 和 Bolts-iOS

Bolts-iOS

  看到这个名字,会不会想到有 Bolts-Android 的存在呢?是的,也确实存在。Bolts 是 Parse 和 Facebook 开源的库,包含 TasksApp Links protocol 两个基础组件。Tasks 即是其 Promise 实现。

PromiseKit

  这个框架是 Max Howell 大牛一个人写的。注:这哥们是 Mac 下著名软件 Homebrew 的作者,没错,传说就是这哥们因为不会写反转二叉树而没拿到 Google offer 的。

  PromiseKit 除了有 Promise 实现外,还有一套基于 Promise 的系统类扩展。

5、实例

  由于 PromiseKit 有一套使用的扩展包,所以本文就用它来举例说明了。

then

  在 OC 的异步操作中,常常会引用一些状态变量:

- (void)confirmPlayTheMoive:(Moive *)moive {
    UIAlertView *alert = [UIAlertView …];
    alert.delegate = self;
    self.willPlayMoive = moive;
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButton:(NSInteger)index {
    if (index != alertView.cancelButton) {
        [self.moive play];
    }
}

  视图控制器的属性应该是用来存储它自身的状态的,而不是存储一下这种临时变量。像上例这个参数 moive ,还得有一个专门的属性 willPlayMoive 来存储它,如果它只在 - (void)confirmPlayTheMoive 方法内部出现就好了。

  如果说是个同步方法的话,那就好说话了:

- (void)confirmPlayTheMoive:(Moive *)moive {
    UIAlertView *alert = [UIAlertView …];
    NSInteger index = [alert showSynchronously];
    if (index != alert.cancelButton) {
        [moive play];
    }
}

  这样,不需要专门的属性来保存这个变量,代码量还减了不少,还更容易理解了。

  不过可惜的是,UIAlertView 中并没有 showSynchronously 这种类似的方法。

  promises 出马咯~

- (void)confirmPlayTheMoive:(Moive *)moive {
    UIAlertView *alert = [UIAlertView …];
    [alert promise].then(^(NSNumber *dismissedButtonIndex){
        [moive play];        
    });

    // cancel 有另外的处理方法
}

  一点击 “确认”,影片就会接着播放啦~

  在 PromiseKit 中,我们用 then 方法来访问 promise value。

  PromiseKit 给 UIAlertViewUIActionSheetNSURLConnectionUIViewController 等很多常用类提供了类似的扩展,还是很方便的。

链式 promises

  在同步世界中,一切都有序地执行着:

NSLog(@"Do A");
NSLog(@"Do B");
NSLog(@"Do C");

  但到了异步代码时,这结构让人感觉跟碗热干面似的:

// 下载数据
[NSURLConnection sendAsynchronousRequest:rq1 queue:q completionHandler:^(id, id data1, id err) {
    // 下载相关数据
    [NSURLConnection sendAsynchronousRequest:rq2 queue:q completionHandler:^(id, id data2, id err) {
        // 下载图片
        [NSURLConnection sendAsynchronousRequest:rq3 queue:q completionHandler:^(id, id dat3a, id err) {
        }];
    }];
}];

  话说,有个小偷,偷到了一个程序员家里,看到了一堆文件,他翻到最后一页,看到了这样的内容:

                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

  这种右漂移的代码,看着感觉怎么样?这样的代码,写起来是爽快,不过别人看起来可就蛋疼了,而且还容易出各种 BUG。

  在 promise 中,咱们可以通过链式调用来避免这种右漂的代码:

[NSURLConnection promise:rq1].then(^(id data1){
    return [NSURLConnection promise:rq2];
}).then(^(id data2){
    return [NSURLConnection promise:rq3];
}).then(^(id data3){
    ...
});

  只要 then 方法中返回一个 promise,就可以像这样进行链式调用了。感觉清爽多了。

  异步代码往往没有同步代码具有可读性。

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSString *md5 = [self md5ForData:data error:nil];
    dispatch_async(dispatch_get_main_queue(), ^{
        self.label.text = md5;
        [UIView animateWithDuration:0.3 animations:^{
            self.label.alpha = 1;
        } completion:^{
            // 最后执行的代码在这里
        }];
        NSLog(@"md5 is: %@", md5);
    });
});

  要找到这最后执行的代码,还得经过好好思考一下才行,而在链式表达式中就没有这样的问题了:

dispatch_promise(^{

    // 在这里,直接返回一个 `NSString`,而不是一个 promise。
    // 像这样返回一个正常的对象,将会直接传到下一个 `next` 方法中。

    return [self md5ForData:data error:nil];

}).then(^(NSString *md5){

    // 这里返回一个 promise,在这个异步方法执行完后,这个 promise 方法的 `next` 才会被执行。

    return [UIView promiseWithDuration:0.3 animations:^{
        self.label.alpha = 1;
    }];

}).then(^{
    // 最后执行的代码在这里
});

  怎么样,看着有没有舒服点?更容易看懂了?

错误处理

  众所周知,异步编程中,错误的处理是比较蛋疼的一件事。如果每个 error 都处理一下的话,不仅写得烦,代码也会难看得要死。所以很多人的选择是,直接无视了它,但显然,这么做并不合适。

  来看下这种代码:

void (^errorHandler)(NSError *) = ^(NSError *error) {
    [[UIAlertView …] show];
};
[NSURLConnection sendAsynchronousRequest:rq queue:q completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    if (connectionError) {
        errorHandler(connectionError);
    } else {
        NSError *jsonError = nil;
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
        if (jsonError) {
            errorHandler(jsonError);
        } else {
            id rq = [NSURLRequest requestWithURL:[NSURL URLWithString:json[@"avatar_url"]]];
            [NSURLConnection sendAsynchronousRequest:rq queue:q completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                UIImage *image = [UIImage imageWithData:data];
                if (!image) {
                    errorHandler(nil); // 其它错误处理方式
                } else {
                    self.imageView.image = image;
                }
            }];
        }
    }
}];

  怎么样,这还只是个小例子,就写着烦,看着也烦。

  在 promise 中,咱们可以统一处理错误:

[NSURLSession GET:url].then(^(NSDictionary *json){
    return [NSURLConnection GET:json[@"avatar_url"]];
}).then(^(UIImage *image){
    self.imageView.image = image;
}).catch(^(NSError *error){
    [[UIAlertView …] show];
})

  这里,只要任何一个地方有过 error,就会直接被最后的 catch 方法里处理,而中间的那些 then 方法也不会被执行了,有木有很方便呢?

组合 when

  咱们常有这种需求:当两个异步操作都完成后,再执行一下个。简单的,可以用一个临时变量来记录:

__block int x = 0;
void (^completionHandler)(id, id) = ^(MKLocalSearchResponse *response, NSError *error){
    if (++x == 2) {
        [self finish];
    }
};
[[[MKLocalSearch alloc] initWithRequest:rq1] startWithCompletionHandler:completionHandler];
[[[MKLocalSearch alloc] initWithRequest:rq2] startWithCompletionHandler:completionHandler];

  呃,这多少有点淡淡的忧伤,在 promisekit 中,咱们可以通过 PMKWhenwhen 来处理这种需求:

id search1 = [[[MKLocalSearch alloc] initWithRequest:rq1] promise];
id search2 = [[[MKLocalSearch alloc] initWithRequest:rq2] promise];

PMKWhen(@[search1, search2]).then(^(NSArray *results){
    [self finish];
}).catch(^{
    // 如果任何一个失败就会来到这里。
});

  PMKWhen 还能通过字典来处理:

id coffeeSearch = [[MKLocalSearch alloc] initWithRequest:rq1];
id beerSearch = [[MKLocalSearch alloc] initWithRequest:rq2];
id input = @{@"coffee": coffeeSearch, @"beer": beerSearch};

PMKWhen(input).then(^(NSDictionary *results){
    id coffeeResults = results[@"coffee"];
});

finally

  promiseKit 不仅提供了 thencatch,还弄了个 finally,顾名思义,也就是最后一定会执行了咯:

[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[self myPromise].then(^{
    //…
}).finally(^{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
})

总结

  可以看到,Promise 确实能简化异步编程,好处多多呀。而且其本身本不复杂难懂,不妨试试。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值