How to handle asynchronous operations in JavaScript?

clock icon

asked 6 months ago Asked

message

1 Answers

eye

16 Views

I'm relatively new to JavaScript and struggling to grasp the concept of asynchronous programming. Can someone explain how to handle asynchronous operations, such as fetching data from an API or reading from a file, using promises or async/await? Any examples would be greatly appreciated!

1 Answers

Here's an example using promises for fetching data from an API:

function fetchData() {
  return new Promise((resolve, reject) => {
    // Simulating an API call
    setTimeout(() => {
      const data = { message: "Data fetched successfully!" };
      resolve(data);
    }, 2000);
  });
}

 

 

Write your answer here

Top Questions