JavaScript Promises: Alternative to then/catch
I promise this won't be a long blog, but no guarantees against puns ๐
The promise
is a prominent way to deal with asynchronous code in JavaScript. Many APIs return asyncronousely and use the promise
as a return value. The promise
is to return data once it's ready.
You can either await
on the promise to be fulfilled or chain a .then()
to tell JavaScript what to do once the promise is fulfilled. Let's consider a method fetchPokemon()
that returns a promise
that fulfills with pokemonData
.
Handling Promises
Here are two general examples of handling promises in javascript.
Using
async/await
const pokemonData = await fetchPokemon(pokemonName) setPokemon(pokemonData)
Using
.then()
chain notationfetchPokemon(pokemonName) .then(pokemonData => setPokemon(pokemonData))
Note: To use async/await
you will need this code to run in an asynchronous function.
Error Handling
We can't forget about error handling! Here is how to error handle with both approaches.
Using async/await
try { const pokemonData = await fetchPokemon(pokemonName) setPokemon(pokemonData) } catch (error) { setError(error) } console.log('completed')
Using .then() chain notation
fetchPokemon(pokemonName) .then(pokemonData => setPokemon(pokemonData)) .catch(error => setError(error)) .finally(() => console.log('completed'))
Depending on the circumstance, folks prefer one versus the other. With async/await
the flow of code is more similar to synchronous code flow.
However, some prefer the chaining syntax for simple circumstances - especially in the useEffect
hook in react.
Alternative to then/catch
Did you know that the .then()
can take two parameters? If you supply the second parameter, it will specify what the code should do when there is an error. This way, you no longer need to provide a .catch()
chain.
Here's the .then()
example from above update:
fetchPokemon(pokemonName)
.then(
pokemonData => setPokemon(pokemonData),
error => setError(error),
)
.finally(() => console.log('completed'))
This is especially nice for simple one-line arrow functions like the ones shown here. Try it out and let me know what you think!