Use of 'then' in ReactJS

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.


I am answering this question bit late but may be helpful to someone at some time.

Let's Start:

From the above code you pasted, I can give you a hint that whenever you see a keyword then in any Javascript code snippet, that is an asynchronous function using promise.

Promise: are objects which store information about whether or not those events have happened yet, and if they have, what their outcome is.Usually, promise will handle success (a.k.a resolve in js code) and failure(a.k.a reject in js code) and also both. So when we create any async functions, the promise is created inside these async functions.

Promise.then: then allows us to assign event handlers to a promise. Depending on the arguments we supply, we can handle success, failure, or both and the return of then is also a promise which means it can handle more events.

And finally to get to the code above, fetchComments is a promise which is an async function, and when the response is resolve it is updating the state of the comments and additionally here we can also handle error scenarios using .catch or even by adding another then

and to end, below link has a nice explanation:

A nice tutorial on Promise and then in javascript is here


Function fetchComments 'll fetch Data and return one Promise then give them to state comments :). But I think you should read here^^.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Tags:

Reactjs