Why are callbacks more “tightly coupled” than promises?

前端 未结 5 1115
Happy的楠姐
Happy的楠姐 2021-01-30 06:51

Can you explain me the following phrase (taken from an answer to Stack Overflow question What are the differences between Deferred, Promise and Future in Javascript?)?

W

5条回答
  •  自闭症患者
    2021-01-30 07:45

    Promises reify the concept of delayed response to something. They make asynchronous computation a first-class citizen as you can pass it around. They allow you to define structure if you want - monadic structure that is - upon which you can build higher order combinators that greatly simplify the code.

    For example you can have a function that takes an array of promises and returns a promise of an array(usually this is called sequence). This is very hard to do or even impossible with callbacks. And such combinators don't just make code easier to write, they make it much easier to read.

    Now consider it the other way around to answer your question. Callbacks are an ad-hoc solution where promises allow for clearer structure and re-usability.

提交回复
热议问题