Categories
JavaScript Answers

How to return values from async functions using async-await from function with JavaScript?

Spread the love

To return values from async functions using async-await from function with JavaScript, we return the resolve value of the promise.

For instance, we write

const getData = async () => {
  const { data } = await axios.get(
    "https://jsonplaceholder.typicode.com/posts"
  );
  return data;
};

(async () => {
  console.log(await getData());
})();

to create the getData function that gets the resolve value of the promise returned by axios.get with await.

We extract the data property from the object returned by the promise and return it.

We then use await with getData to get the resolve value of the promise that was returned with return in getData.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *