An Interest In:
Web News this Week
- April 26, 2024
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
February 28, 2021 11:19 pm GMT
Original Link: https://dev.to/gladyspascual/re-writing-then-catch-to-async-await-2l02
Re-writing then/catch to async/await
There are two main ways to handle asynchronous code in JavaScript:
- then/catch (ES6), and
- async/await (ES7).
In this post, I wanted to show to convert a then/catch syntax into an async/await syntax.
In this example, I will be using axios, a JavaScript library that allows making an HTTP request, and an alternative to the .fetch()
method. Some of the advantages of using axios over the fetch method are that axios performs automatic transforms of JSON data and has better browser support compared to the fetch method.
then/catch
useEffect(() => { axios .get( `https://finnhub.io/api/v1/news?category=general&token=${process.env.REACT_APP_API_KEY}` ) .then((response) => { setCurrentNews(response); setLoading(false); }) .catch((err) => console.log("Error fetching and parsing data", err)); }, []);
Enter fullscreen mode Exit fullscreen mode
async/await
useEffect(() => { async function fetchCurrentNewsData() { const result = await axios.get( `https://finnhub.io/api/v1/news?category=general&token=${process.env.REACT_APP_API_KEY}` ); setCurrentNews(result); setLoading(false); } fetchCurrentNewsData(); }, []);
Enter fullscreen mode Exit fullscreen mode
I hope this helps. Some may argue that the async/await syntax is more readable compared to the then/catch syntax. What are your thoughts? Let me know in the comments below if you have a preferred syntax
Original Link: https://dev.to/gladyspascual/re-writing-then-catch-to-async-await-2l02
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To