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
});
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With