Skip to content

Latest commit

 

History

History
47 lines (36 loc) · 1.33 KB

promises-over-callbacks.md

File metadata and controls

47 lines (36 loc) · 1.33 KB
id sidebar_label title description keywords version image
promises-over-callbacks
Promises over callbacks
Promises over callbacks
Promises over callbacks | React Patterns, techniques, tips and tricks in development for React developers.
promises over callbacks
reactpatterns
react patterns
reactjspatterns
reactjs patterns
react
reactjs
react techniques
react tips and tricks
Promises over callbacks
/img/reactpatterns-cover.png

For HTTP Request, our existing solution is to use callbacks.

request(url, (error, response) => {
  // handle success or error.
});

doSomethingElse()

A few problems exist with callbacks. One is known as callback hell. A larger problem is decomposition.

The callback pattern require us to specify the task and the callback at the same time. By difference, promises allow us to specify and dispatch the request in one place.

promise = fetch(url) // fetch is a replacement for XMLHttpRequest

And then add the callback later, and in a different place.

promise.then(response => {
  // handle the response
})

This also allows us to attach multiple handlers to the same task.

promise.then(response => {
  // handle the response.
})

promise.then(response => {
  // do something else with the response.
})