DEV Community

Ranjith srt
Ranjith srt

Posted on

js - Async & Await


  function fetchData() {

  return new Promise((resolve) => {

    setTimeout(() => {

      const data = { id: 1, name: "Jane Doe" };

      resolve(data);
    }, 2000);
  });
}

fetchData().then((result) => {

  console.log(result);
});


Enter fullscreen mode Exit fullscreen mode

without async


function getUser() {

  console.log("Fecthing Data...");

  try {

    const data = fetchData();

    console.log("Data Fetched:", data);

  } catch (error) {
    console.log(error);
  }
}

getUser();

Enter fullscreen mode Exit fullscreen mode

async function getAsyncUser() {

  console.log("Fecthing Data...");

  try {
    const data = await fetchData();

    console.log("Data Fetched:", data);
  } catch (error) {
    console.log(error);
  }
}

getAsyncUser();


Enter fullscreen mode Exit fullscreen mode

Top comments (0)