One, common asynchronous programming are
- 1. Callback function
- 2、
promise
- 3. Event monitoring/publish and subscribe
- 4、
rxjs
Second, the comparison of using promise
and rxjs
implementing asynchronous programming
-
1. Use
promise
asynchronous programmingconst promise = new Promise((resolve, reject) => { setTimeout(() => { resolve('promise成功了'); }, 1000); }); promise.then(data => { console.log(data); });
-
2. Use
rxjs
asynchronous flow programmingimport { Observable } from 'rxjs'; const stream = new Observable(observer => { setTimeout(() => { observer.next('rxjs成功了'); }); }); stream.subscribe(data => { console.log(data); });
2. rxjs
You can cancel the subscription, but promise
not
-
1. Specific implementation code
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);
Three, asynchronous multiple execution
For
promise
the implementation of a state to another state it is immutable after the results but forresole
thatreject
, but can not be rolled back
-
1.
promise
The timer in [execute only once]const promise = new Promise((resolve, reject) => { setInterval(() => { resolve('promise成功了'); }, 1000); }); promise.then(data => { console.log(data); });
-
2. Use
rxjs
multiple executionsimport { 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); });
Four, common operators
-
1. How to use
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. See the official website address for common operators
Creation Operators
Operation symbol for creating asynchronous flowJoin Creation Operators
Connection creationTransformation Operators
Data conversionFiltering Operators
Filter dataJoin Operators
Concatenated operatorMulticasting Operators
Error Handling Operators
Utility Operators
Conditional and Boolean Operators
Mathematical and Aggregate Operators
-
3. For example, filter channels that limit the click rate
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));