What is the difference between Promises and Observables?

后端 未结 30 3097
小鲜肉
小鲜肉 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条回答
  •  长情又很酷
    2020-11-22 00:26

    There is one downside of Observables missing in the answers. Promises allow to use the ES7 async/await functions. With them you can write asynchronous code like it would be a synchronous function call, so you don't need callbacks anymore. The only possibility for Observables to do this, is to convert them to Promises. But when you convert them to Promises, you can only have one return value again:

    async function getData(){
        const data = await observable.first().toPromise();
        //do stuff with 'data' (no callback function needed)
    }
    

    Further reading: How can I `await` on an Rx Observable?

提交回复
热议问题