promise和Rxjs的一點區別

promise 代碼 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只能發射一次spa

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等code

相關文章
相關標籤/搜索