0

I have a fetch method:

async fetch {
    return await axios.get('/api/users');
}

This is called:

let data = this.fetch();
console.log(data);

But the log is a promise - how can I get the log after the method call to log the data and not the promise, I thought async/await would wait for the promise to resolve?

panthro
  • 22,779
  • 66
  • 183
  • 324
  • I think the fetch "method" is missing some syntax. Also I think the async/await is unnecessary as it returns a promise. Consider using `let data = await this.fetch()`? – evolutionxbox Feb 23 '21 at 11:05
  • An [async function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function) always returns a promise. – Reyno Feb 23 '21 at 11:13

2 Answers2

1
async fetch {
    const res = await axios.get('/api/users');
    return await res.data;
}
Shuvo
  • 1,253
  • 9
  • 18
0

To read the data from a promise you must wait for it to finish executing. You can use the .then() function to log the data.


let data = this.fetch();

data.then(result => {
    console.log(result);
});

You can read further about promises here.

Josh Hales
  • 394
  • 2
  • 12