DEV Community

loading...
Cover image for Re-writing then/catch to async/await

Re-writing then/catch to async/await

gladyspascual profile image Gladys Pascual ・1 min read

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) => {
        const firstTenNews = response.data.slice(0, 10);
        setCurrentNews(firstTenNews);
        setLoading(false);
      })
      .catch((err) => {
        console.log("Error fetching and parsing data", err);
        setLoading(false);
      });
  }, []);
Enter fullscreen mode Exit fullscreen mode

async/await

  useEffect(() => {
    async function fetchCurrentNewsData() {
      try {
        const result = await axios.get(
          `https://finnhub.io/api/v1/news?category=general&token=${process.env.REACT_APP_API_KEY}`
        );
        const firstTenNews = result.data.slice(0, 10);
        setCurrentNews(firstTenNews);
        setLoading(false);
      } catch (err) {
        console.log("Error fetching and parsing data", err);
        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 👩🏻‍💻

Discussion (3)

pic
Editor guide
Collapse
thomasrosen profile image
Thomas Rosen

What about the error handling in the async/await example?
Would I need a try/catch block? Or is the error expected to bubble to the uppermost catch?

Collapse
sebbdk profile image
Sebastian Vargr • Edited

Async functions are just syntactical-sugar for Promises last I checked, so yes you need a try/catch. :)

Collapse
gladyspascual profile image
Gladys Pascual Author

That's a good 'catch' 😎 I've added the try/catch on the async/await syntax there, thanks for highlighting 🙌🏽