What is the difference between Promises and Observables?

后端 未结 30 2691
小鲜肉
小鲜肉 2020-11-21 23:48

What is the difference between Promise and Observable in Angular?

An example on each would be helpful in understanding both the cases. In w

30条回答
  •  梦毁少年i
    2020-11-22 00:43

    I see a lot of people using the argument that Observable are "cancellable" but it is rather trivial to make Promise "cancellable"

    function cancellablePromise(body) {
      let resolve, reject;
      const promise = new Promise((res, rej) => {
        resolve = res; reject = rej;
        body(resolve, reject)
      })
      promise.resolve = resolve;
      promise.reject = reject;
      return promise
    }
    
    // Example 1: Reject a promise prematurely
    const p1 = cancellablePromise((resolve, reject) => {
      setTimeout(() => resolve('10', 100))
    })
    
    p1.then(value => alert(value)).catch(err => console.error(err))
    p1.reject(new Error('denied')) // expect an error in the console
    
    // Example: Resolve a promise prematurely
    const p2 = cancellablePromise((resolve, reject) => {
      setTimeout(() => resolve('blop'), 100)
    })
    
    p2.then(value => alert(value)).catch(err => console.error(err))
    p2.resolve(200) // expect an alert with 200

提交回复
热议问题