0

I've trying to retrieve the data, but I can't return it, can only see it in the console, it's a simple axios get function but for some reason, I keep getting Promise even after using async/await.

my goal is to save the data to the memory.

any help would really be appreciated

    let fetchTodo = async () => {
    
        await axios.get('https://jsonplaceholder.typicode.com/todos/1')
            .then(res => console.log(res.data))
            .then(res => { return res })
            .catch(err => console.log(err))
    };

console.log("TEST: ", fetchTodo())

console

zee
  • 11
  • 1
  • 4

3 Answers3

0

Asycn function always returns a promise, to get data from the fetchTodo function you need to create another async function which will await the result returned by fetchTodo(). if you are using react, you can use states and update the state while you are inside the .then chain of the fetchTodo function.

Bilal Mohammad
  • 129
  • 1
  • 13
0

The async/await syntax means a function will return a Promise.

If you want to return the value, you could do something like this:

let fetchTodo = async () => {
  try {
    const res = await axios.get("https://jsonplaceholder.typicode.com/todos/1");
    return res;
  } catch (error) {
    console.log(error);
  }
};

// For the folowing code to work, it must be placed inside a async  function as well
const res = await fetchTodo();
console.log(`Test: ${res.data}`);

// If it's a Top level call, use the folowing code
const res = fetchTodo().then( res => {
    const data = res.data;
    // The rest of your code goes here.
    // ...
    // ...
    // ...
}).catch( error => {
    console.log(error);
});

Some more information about it on: How can I use async/await at the top level?

yuridamata
  • 459
  • 1
  • 5
  • 13
  • I tried that approach but still, the second async/await function is returning a pending promise. I am trying to save the returned value to the memory – zee Aug 26 '21 at 21:00
  • I believe the edited answer will help you. – yuridamata Aug 27 '21 at 16:09
0

Asycn function always returns a promise. For getting or saving data you need to get it from .then() function. Here you can check the example. Hope so it will help you.

let fetchTodo = async () => {
        await axios.get('https://jsonplaceholder.typicode.com/todos/1')
            .then(res => console.log(res.data))
            .then(res => { 
                  // here you can performance your task, save data, send 
                  // response or anything else
                  return res 
             })
            .catch(err => console.log(err))
           };

fetchTodo()