I'm using fetch to grab data from a json file. In a .then(), I call a callback to do something with that data, and then eventually return the final value from the callback. The problem is that, when I return, it returns a promise instead of the final value. I've looked through other similar questions, and thought I had the asynch concepts down, but I'm still stuck on this. Is there something I'm missing?
const func = (callback) => {
fetch('https://asdf.json')
.then(response => {
return response.json();
})
.then(data => {
return callback(data)
}
}
const callBack = (parsedData) => {
//do something to get finalValue
return finalValue
}
func(callBack);
I should add that, I tried just calling callback(data) without the return, but this just returned undefined.
fetch method returns a promise, so you must use async/await or then() to make it works properly. For example:
const func = (callback) => {
return fetch('asdf.json')
.then(response => {
return response.json();
})
.then(data => {
return callback(data)
})
}
const callBack = (parsedData) => {
//do something to get finalValue
return parsedData;
}
const main = async () => {
console.log(await func(callBack));
}
main();
Using then():
const func = (callback) => {
return fetch('asdf.json')
.then(response => {
return response.json();
})
.then(data => {
return callback(data)
})
}
const callBack = (parsedData) => {
//do something to get finalValue
return parsedData;
}
func(callBack).then(response=> {
console.log(response);
})