angular2 学习笔记 , Rxjs, Promise, Async/Await 的区别

更新 2019-07-17

function abc(): Promise<string>{
  return new Promise(resolve => {
     resolve('dada');
     console.log('yeah')
  });
}

resolve 之后你再调用 resolve 外部是不会理会的, 这和 .next 不同

另外 resolve 也不等于 return;

resolve 之后的代码依然会执行.

Promise 是 ES 6

Async/Await 是 ES 7

Rxjs 是一个 js 库

在使用 angular 时,你会经常看见这 3 个东西.

它们都和异步编程有关,有些情况下你会觉得用它们其中任何一个效果都一样. 但又觉得好像哪里不太对....

这篇就来说说,我在开发时的应用方式.

在 Typescript 还没有支持 Async/Await 的时候, angular 就已经发布了.

那时我们只想着 Promise vs Rxjs

这 2 者其实很好选择, 因为 "可读性" 和 "代码量" 是差不错的.

而 Rxjs 有一些 Promise 没有的特性.

比如一堆的 operator, 这让我们很方便的操作 stream, 这是 Promise 没有的. (可以去看看如何用 rxjs 来实现 search text, triple click 等等, 几行代码就可以完成了)

此外 Rxjs 可以持续的监听和响应, 这点也是 Promise 做不到的.

所以绝大部分情况下,我们鼓励开发者使用 Rxjs.

而在 angular 自带的多种方法中,默认返回的也都是 Rxjs.

结论是 :

a.如果要持续监听和响应或则要用 operator 那么一定是选 Rxjs

b.其它情况就对比 2 者的 "可读性" 和 "代码量" (在没有 Async/Await 的年代, 它们是一样的), 所以还是选 Rxjs 就对了.

后来, Typescript 支持了 Async/Await

这让情况发生了变化.

Async/Await 的 "可读性" 是比 Promise 要好的 (代码越复杂,可读性就越好)

所以刚刚的结论 a 依然没有改变

但是结论 b 就有了变数.

下面我们来看看对比的代码

我们说 Async/Await 可读性高是指 "它的返回方式和我们写同步代码很相似"

let a = getData(); // 同步代码

let a = await getDataAsync(); // Async/Await 代码 

这是它好读的原因.

但是呢.. 当我们加上错误处理时,它也许就没有那么好了.

async click()
{
    try
    {
        let a = await getDataAsync();
    }
    catch(e)
    {
        // handle error 
    }    
}

Async/Await 是用 catch 来捕获的.

这和 java, c# 类似, 读起来还算可以, 但是如果你有多个异步代码, 而且要不同的错误处理呢 ?

async click()
{
    try
    {
        let a = await this.http.get('urlA');
        let b = await this.http.get('urlB');
        let c = await this.http.get('urlC');
    }
    catch(e)
    {
        // 我们需要在这里识别出不同的 error 做不同的处理 
    }    
}

把成功和失败的逻辑分开, 并不会让代码更好读, 而且还需要写识别错误的逻辑...

所以我们可以这样写

async click()
{
    try
    {
        let a = await this.http.get('urlA').catch(e => {
            this.errorMessage = 'A failed';
            throw '';
        });
        let b = await this.http.get('urlB').catch(e => {
            this.errorMessage = 'B failed';
        });
        let c = await this.http.get('urlC');
    }
    catch(e)
    {
        // 什么都不处理 
    }    
}

勉强还行... 但是为什么 .catch 里面还需要 throw 呢 ? 为什么有一个 "什么都不处理呢" ?

这是因为

let a = await this.http.get('urlA').catch(e => {     
    this.errorMessage = 'A failed';    
    // 假设没有 throw, let a 会是 undefined, let b, let c 会继续执行... 
    // 假设 return whatever, let b, let c 也会执行. 
    // 你要中断 let b, let c 只有 2 个方法. 
    // 1. throw '';
    // 2. Promise.reject('');
    // 这是 Async/Await 和 Promise 不同的地方
});

一旦你 throw 了, 外面就要有人 catch 不然就会 throw 到 angular 的 catch 里头了 (注意我的 click 是 component 的方法).

所以就有了一个

catch(e)
{
    // 什么都不处理, 其实是为了防止 throw 到 angular 的 catch 里头 /.\ 
}    

写 Promise 是不需要 try catch 的,因为 Promise 一旦进入 reject 就不可能进入下一个 then 了, 而 Async/Await 需要配搭 try catch throw.

结论 :

a.如果要持续监听和响应或则要用 operator 那么一定是选 Rxjs

b.其余情况就看个人了

-看惯了 Promise, 又看不惯 try catch 的话建议用 Promise 就好了.

-但如果 2 种方式你都看的习惯, 那么建议写 Async/Await 吧

因为看不惯 Promise 的人, 你写 Promise, 他就死了.

可是看不惯 try catch 的人, 你写 try catch, 他还死不了.

另外,

Rxjs 有一个 toPromise 的功能, 这有时候让人很困惑的...

要知道 Rxjs.toPromise() 只有在 rxjs.complete 时才会触发.

也就是说如果一个 rxjs 它需要持续监听, 那么你用 toPromise 就会毁了. 一定要用 subscribe

angular 的 http 发了 ajax 后就会 complete 了, 所以你可以使用 toPromise, 但是 ActivatedRoute.paramMap 你 toPromise 就完蛋了, 它不会 complete 所以也就不会触发你的 promise 事件.