Long story short, in order to return response in Async function, you either need a callback or use async/await structure.

Case 1: Using callback –

Callback is the function which runs after asynchronous function completed successfully. Consider this code example –

superhero.json

{
  avenger1: 'Captain America',
  avenger2: 'Ironman',
  avenger3: 'Hulk',
  avenger4: 'Hawkeye',
}
var data = {};
const callback = (data) => {
  console.log(data);
  // Output: {avenger1: 'Captain America' ...}
}

fetch('/superhero.json')
  .then(response => response.json())
  .then(data => callback(data));

console.log(data) // Output: {}

From the above code, you can understand the flow of asynchronous functions. We are fetching superhero.json from remote server. Calling something from server takes more time than running code on local machine. That’s why our data variable is still empty after fetch call. Because fetch is not yet completed and our code moved to the next line.

Case 2: Using async/await

To simplify things for developers and give them a feel of synchronous coding, javascript came up with a format async/await. Here you do not use callbacks, else code like synchronous. Check this example –

const superhero = async () => {
  const response = await fetch('/superhero.json');
  const data = await response.json();
  return data;
}

There are two properties of async/await –

  1. You can only use await within the function which is marked async.
  2. After using await, you can use the variable in further code, within the function, as like as normal flow. So, above superhero function will return data only after it successfully get from fetch.

    Tweet this to help others

Live Demo

Comments

About the Author

akamit

I am Akash Mittal, an overall computer scientist. If you want to guest post, need help in your projects, want to advertise, Feel free to contact me at [email protected]

View All Articles