When to use Promise over observable?

前端 未结 5 1697
梦毁少年i
梦毁少年i 2021-02-13 04:56

Is there any case, where Promise is more powerful as compare to observable? I know a lot of benefits of observables over promises. But Is there any case, I should use only promi

5条回答
  •  遥遥无期
    2021-02-13 05:07

    Observable is lazy --> nothing will happen until we subscribed the observable. Observable can be cancelled at anytime by unsubscribing it for memory clean up. Promise can have only one response but observable can have more than one responses.

    const promSingle = new Promise(resolve){
      resolve('a');
      resolve('b');
    }
    promSingle.then(value => {
      console.log(value)
    })
    

    Print only a In Observable :

    const obSerMult = new Observable(observable){
      Observable.next('a');
      Observable.next('b');
      Observable.next('c');
      Observable.next('d');
    }
    
    obSerMult.subscribe(value => {
      console.log(value);
    })
    
    print will be a, b , c ,d
    

提交回复
热议问题