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 对象已经处于 fulfilled 或 rejected 状态,那么相应的方法将会被立刻调用, 所以在异步操作的完成情况和它的绑定方法之间不存在竞争条件。)

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

4、PromiseKit 和 Bolts-iOS

Bolts-iOS

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

PromiseKit

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

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

5、实例

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

then

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

 
 
 
 
 
 

Objective-C

 
1
2
3
4
5
6
7
8
9
10
11
12
13
- (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 方法内部出现就好了。

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

 
 
 
 
 

Objective-C

 
1
2
3
4
5
6
7
8
- (void)confirmPlayTheMoive:(Moive *)moive {
    UIAlertView *alert = [UIAlertView …];
    NSInteger index = [alert showSynchronously];
    if (index != alert.cancelButton) {
        [moive play];
    }
}
 

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

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

  promises 出马咯~

 
 
 
 
 
 

Objective-C

 
1
2
3
4
5
6
7
8
9
- (void)confirmPlayTheMoive:(Moive *)moive {
    UIAlertView *alert = [UIAlertView …];
    [alert promise].then(^(NSNumber *dismissedButtonIndex){
        [moive play];        
    });
 
    // cancel 有另外的处理方法
}
 

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

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

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

链式 promises

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

 
 
 
 
 

Objective-C

 
1
2
3
4
NSLog(@"Do A");
NSLog(@"Do B");
NSLog(@"Do C");
 

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

 
 
 
 
 
 

Objective-C

 
1
2
3
4
5
6
7
8
9
10
// 下载数据
[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) {
        }];
    }];
}];
 

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

 
 
 
 
 

Objective-C

 
1
2
3
4
5
6
7
8
9
10
11
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
 

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

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

 
 
 
 
 

Objective-C

 
1
2
3
4
5
6
7
8
[NSURLConnection promise:rq1].then(^(id data1){
    return [NSURLConnection promise:rq2];
}).then(^(id data2){
    return [NSURLConnection promise:rq3];
}).then(^(id data3){
    ...
});
 

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

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

 
 
 
 
 
 

Objective-C

 
1
2
3
4
5
6
7
8
9
10
11
12
13
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);
    });
});
 

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

 
 
 
 
 
 

Objective-C

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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 都处理一下的话,不仅写得烦,代码也会难看得要死。所以很多人的选择是,直接无视了它,但显然,这么做并不合适。

  来看下这种代码:

 
 
 
 
 
 

Objective-C

 
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
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 中,咱们可以统一处理错误:

 
 
 
 
 
 

Objective-C

 
1
2
3
4
5
6
7
8
[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

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

 
 
 
 
 
 

Objective-C

 
1
2
3
4
5
6
7
8
9
__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 中,咱们可以通过 PMKWhen 和 when 来处理这种需求:

 
 
 
 
 
 

Objective-C

 
1
2
3
4
5
6
7
8
9
id search1 = [[[MKLocalSearch alloc] initWithRequest:rq1] promise];
id search2 = [[[MKLocalSearch alloc] initWithRequest:rq2] promise];
 
PMKWhen(@[search1, search2]).then(^(NSArray *results){
    [self finish];
}).catch(^{
    // 如果任何一个失败就会来到这里。
});
 

  PMKWhen 还能通过字典来处理:

 
 
 
 
 
 

Objective-C

 
1
2
3
4
5
6
7
8
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 不仅提供了 then 和 catch,还弄了个 finally,顾名思义,也就是最后一定会执行了咯:

 
 
 
 
 
 

Objective-C

 
1
2
3
4
5
6
7
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[self myPromise].then(^{
    //…
}).finally(^{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
})
 

最新文章

  1. 学习tensorflow之mac上安装tensorflow
  2. Android存储空间不足的解决办法
  3. 在C#中使用C++编写的类
  4. sql行列转换
  5. Redis学习手册(Key操作命令)
  6. 第一发。。。codeforces 609 C Load Balancing 贪心
  7. Codeforces 713D Animals and Puzzle
  8. 【IHttpHandler】在ASP.Net2.0中使用UrlRewritingNet实现链接重写
  9. IE8按F12不显示开发人员工具窗口
  10. [AngularJS] Accessing The View-Model Inside The link() When Using controllerAs
  11. PHP连接Mysql服务器的操作
  12. 由一个LED闪烁问题发现的MTK的LED driver中存在的问题
  13. BZOJ 3924: [Zjoi2015]幻想乡战略游戏(动态点分治)
  14. [django]urls.py 中重定向
  15. 第八节,配置分布式TensorFlow
  16. Linux中的其他命令
  17. [leetcode]250. Count Univalue Subtrees统计节点值相同的子树
  18. PAT甲 1006. Sign In and Sign Out (25) 2016-09-09 22:55 43人阅读 评论(0) 收藏
  19. spring下redis使用资料
  20. MySQL 四种链接

热门文章

  1. QTimer的用法
  2. 使用Flask设计带认证token的RESTful API接口[翻译]
  3. linux top命令结果参数详解
  4. java设计模式- (1)单例模式
  5. 使用jOrgChart插件实现组织架构图的展示
  6. 如何查看当前Ubuntu系统的版本
  7. FineUI(专业版)v3.0.0 发布,手机、平板和桌面全支持!
  8. markdown语法说明
  9. StringHelper
  10. springmvc:jsp fmt标签格式化Date时间,格式化后可以用于页面展示