본문 바로가기
Javascript

Async Functions in Javascript

by Doromi 2024. 4. 1.
728x90
반응형
import React, { useState, useEffect } from 'react';

function DataFetcher() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    async function fetchData() {
      try {
        const data = await fetchData('https://api.example.com/data');
        setData(data);
        setLoading(false);
      } catch (error) {
        setError(error);
        setLoading(false);
      }
    }

    fetchData();
  }, []);

  if (loading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>Error: {error.message}</div>;
  }

  return (
    <div>
      {data.map(item => (
        <div key={item.id}>{item.name}</div>
      ))}
    </div>
  );
}

export default DataFetcher;

 

Q: What is the difference between async/await and Promises?

A: Both async/await and Promises are ways to handle asynchronous code in JavaScript. Async/await is a syntactic feature introduced in ES8 that makes it easier to write and read asynchronous code. It's built on top of Promises, allowing you to use the await keyword to pause the execution of an async function until a Promise is resolved or rejected.

Q: Can I use async/await in a React component's render method?

A: No, you cannot use async/await directly in a React component's render method. The render method should be synchronous and should not contain any side effects. You should use async functions in the appropriate lifecycle methods or hooks, as shown in the examples above.

Q: What is the recommended way to handle async functions in React?

A: In functional components, using the useEffect hook in combination with the useState hook is the recommended way to handle async functions. In class components, using the componentDidMount lifecycle method is the most common approach.

Q: How can I handle errors in async functions?

A: When using async/await, you can handle errors by wrapping your code in a try/catch block. This will catch any exceptions thrown by rejected promises and allow you to handle them gracefully.

 

 

Reference : https://codedamn.com/news/reactjs/handle-async-functions-with-ease

728x90
반응형

'Javascript' 카테고리의 다른 글

OOP(5)  (0) 2023.11.07
OOP(4)  (0) 2023.11.06
OOP(3)  (0) 2023.11.05
OOP(2)  (0) 2023.11.05
OOP  (0) 2023.11.05