Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of 'then' in ReactJS

Tags:

reactjs

For ease in explaining the significance of 'then', could anyone tell me what is happening in this code?

fetchComments().then(response => {
      this.setState({
        comments: response.comments
      });
    });
like image 918
Sagun Raj Lage Avatar asked Sep 01 '17 12:09

Sagun Raj Lage


1 Answers

fetchComments returns a promise (probably; it could just be a "thenable"*). A promise is something that will be either resolved or rejected at a later point in time (typically**). then is used to hook up a handler that will be called when the promise is resolved (and optionally when it's rejected, if you pass a second function into then; otherwise you'd use catch).

In this case, that code says that when/if the promise returned by fetchComments resolves, use the resolution value to set the state of the React component using the comments property of that resolution value.

More about promises in this MDN article and in the Promises/A+ spec.


* See the Promises/A+ spec for what a "thenable" is.

** If you use then on a promise that's already resolved or rejected, you're guaranteed by the native promises in JavaScript that your handler will still be called asynchronously. That wasn't always the case with some early promise-like implementations, which would either call your callback asynchronously (if the promise wasn't already settled) or synchronously (if it was), which was...chaotic and unhelpful. JavaScript's native promises and any really good promise library guarantees consistent callback behavior.

like image 162
T.J. Crowder Avatar answered Sep 30 '22 00:09

T.J. Crowder