promise 程式碼
let promise = new Promise( (resolve) => { setTimeout(() => { resolve('chen'); },2000) }); promise.then((value) => { console.log(value); })
Rxjs程式碼
let start = new Observable( (observer) => { let timeOut = setTimeout( () => { observer.next('chen2'); },4000) }) let str = start.subscribe( (value) => { console.log(value); })
區別1: rxjs可以取消subscribe,promise不可以
setTimeout( () => { str.unsubscribe(); },1000)
區別2: rxjs可以發射多次,promise只能發射一次
let setTime2; let start2 = new Observable( (observable) => { let count = 0; setTime2 = setInterval( () => { observable.next(count++); },1000) }) let str2 = start2.subscribe( (num) => { console.log(num); if(num > 10){ str2.unsubscribe(); clearInterval(setTime2); } })
區別3: rxjs 自帶了許多的工具函式,如filter等