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.
– user8811593
Answered @user8811593 ...
– novic