一、常见的异步编程有
- 1、回调函数
- 2、
promise
- 3、事件监听/发布订阅
- 4、
rxjs
二、使用promise
和rxjs
实现异步编程的对比
-
1、使用
promise
异步编程的写法const promise = new Promise((resolve, reject) => { setTimeout(() => { resolve('promise成功了'); }, 1000); }); promise.then(data => { console.log(data); });
-
2、使用
rxjs
异步流编程的写法import { Observable } from 'rxjs'; const stream = new Observable(observer => { setTimeout(() => { observer.next('rxjs成功了'); }); }); stream.subscribe(data => { console.log(data); });
二、rxjs
可以取消订阅,但是promise
却不可以
-
1、具体实现代码
import { Observable } from 'rxjs'; const stream = new Observable(observer => { setTimeout(() => { observer.next('请求成功'); }, 2000); }); const disposable = stream.subscribe(data => { console.log(data); }); setTimeout(() => { disposable.unsubscribe(); // 取消订阅 }, 1000);
三、异步多次执行
对于
promise
的执行是一个状态到另外一个状态后是不可变的,结果要不是resole
就是reject
,但是不能回退
-
1、在
promise
中的定时器【只执行一次】const promise = new Promise((resolve, reject) => { setInterval(() => { resolve('promise成功了'); }, 1000); }); promise.then(data => { console.log(data); });
-
2、使用
rxjs
多次执行import { Observable } from 'rxjs'; const stream = new Observable(observer => { let count: number = 0; setInterval(() => { observer.next(count++); }, 1000); }); const disposable = stream.subscribe(data => { console.log(data); });
四、常见的操作符
-
1、使用方式
import { Observable } from 'rxjs'; import { map, filter } from 'rxjs/operators'; const stream = new Observable() < number > (observer => { let count = 0; setInterval(() => { observer.next(count++); }, 1000); }); stream .pipe( filter((x: number) => x % 2 === 0), map((x: number) => x * 2) ) .subscribe(data => { console.log(data); });
-
2、常见的操作符见官网地址
-
Creation Operators
创建异步流的操作符号 -
Join Creation Operators
连接创建 -
Transformation Operators
数据转换的 -
Filtering Operators
过滤数据 -
Join Operators
连接的操作符 Multicasting Operators
Error Handling Operators
Utility Operators
Conditional and Boolean Operators
Mathematical and Aggregate Operators
-
-
3、比如限制点击评率的过滤管道
import { fromEvent } from 'rxjs'; import { throttleTime } from 'rxjs/operators'; const clicks = fromEvent(document, 'click'); // 限制1000ms内不能重复点击 const result = clicks.pipe(throttleTime(1000)); result.subscribe(x => console.log(x));