fetch api to return actual data not promise

Viewed 48

How do I get my getData() function to actually return the data. At the moment I get a console log of a promise object

function getData() {
    fetch('//some api url')
        .then(response => response.json())
        .then(data => { return data })
};

export const data = getData();
console.log(data); // returns promise, not actual object
1 Answers

You can't just wait for asynchronous code without await

function getData() {
  return fetch('//some api url')
    .then(response => response.json())
    .then(data => {
      return data
    })
};

getData().then(console.log)

function getData() {
  return fetch('//some api url')
    .then(response => response.json())
    .then(data => {
      return data
    })
};

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

Related