Why is fetch returning a file and not the data?

Asked

Viewed 299 times

0

I’m doing a fetch to get the data of a JSON, but the variable is getting the value of promisse and not the returned data.

var data = fetch('./data/data.json')
    .then((response) => response.json())
    .then(result => { return result; });

console.log(data);

How could I do to return the data and not the Promise?

1 answer

2

You are doing wrong, return example json

fetch('./data.json')
  .then(response => {
    return response.json()
  })
  .then(data => {
    // Work with JSON data here
    console.log(data)
  })
  .catch(err => {
    // Do something for an error here
  })

that is, in this code has a method then has a console.log(data) and the outcome that expected, and is not the data that really is a promisse, in his code:

var data = fetch('./data/data.json')
    .then((response) => response.json())
    .then(result => { console.log(result); });

the variable result is the feedback you need that will bring the data from the json.

Reference: Doc. By Using Fetch

How the user wants to redeem the value make a callback Function:

function res(data) {
    // utiliza o valor aqui ...
}

var data = fetch('./data/data.json')
    .then((response) => response.json())
    .then(result => { res(result); });

or else async/await:

var data = await fetch('./data/data.json');
var result = await data.json();

if you are inside a function you have to put a async to solve the promisses example:

async function resultJson(){
    var data = await fetch('./data/data.json');
    return await data.json();
}

Reference: Async And Await to the Rescue

Remember that all this depends on how you are implementing and also check the best way to do for your context.

  • Virgilio Novic thank you so much for your attention, but how do I throw the dice out of the scope of fetch? The intention would be that var data would be in a global scope.

  • Answered @user8811593 ...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.