Back

Technologies:

javascriptjavascript
reactjsreactjs
avatar
Tolerim
a month ago

The array of objects that is returned transforms into a promise.

This question already has answers here:
How do I return the response from an asynchronous call? (41 answers) Closed 2 years ago.
What is the proper way to get a value from an asynchronous function?

const axios = require('axios');
async function getData() {
  const data = await axios.get('https://jsonplaceholder.typicode.com/posts');
  return data;
}
console.log(getData());
However, this code returns:

Promise { <pending> }
Answers(2)
avatar
Vogi
a month ago
Verified Answer
The reason you are seeing Promise { } is because the function getData() is asynchronous and returns a promise. A promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. To get the value from the promise, you can use either .then() or await. Here's how you can use .then():
async function getData() {
  const data = await axios.get('https://jsonplaceholder.typicode.com/posts');
  return data;
}
getData().then((data) => {
  console.log(data);
});
Here's how you can use await:
async function getData() {
  const data = await axios.get('https://jsonplaceholder.typicode.com/posts');
  return data;
}
(async () => {
  const data = await getData();
  console.log(data);
})();
I hope this helps! Let me know if you have any other questions.

Sources

async function - JavaScript | MDN - Mozilla Developerjavascript - How to return values from async functions using async ...How to Get Return Value From Asyncio CoroutineHow do I retrieve value from async function in react?How to get value from async function? - Stack Overflow
avatar
Tolerim
a month ago
The reason you get Promise { } as a value when you try to log the result of your async function is because async functions return Promises. In order to get the actual value from the Promise, you need to use either the then method or await keyword. Here are two ways you can modify your code to get the data: Using then method:
const axios = require('axios');
async function getData() {
  return axios.get('https://jsonplaceholder.typicode.com/posts');
}
getData().then((data) => console.log(data));
Using await keyword:
const axios = require('axios');
async function getData() {
  const data = await axios.get('https://jsonplaceholder.typicode.com/posts');
  return data;
}
(async () => {
  console.log(await getData());
})();
Both of these implementations will log the actual value retrieved from the asynchronous operation.
;