How can I use an object outside of a function that utilizes .fetch and promises?
If I have:
getBuildList();
function getBuildList(){
fetch('http://127.0.0.1:8000/builds/buildStatsAPI')
.then(function(res){
return res.json();
})
.then(function(data) {
initialLoad(data);
})
.catch(function(err){
console.log(err);
});
}
I want to use data
outside of this functions scope.
I have tried to add return data
pretty much everywhere inside this function, but cannot seem to make it available outside the scope of this function.
Ideally I only want to fetch this data once from the API, then re-use the fetched data with different functions when buttons are pressed on the DOM.
I have tried (among many others):
getBuildList();
let jsonData = getBuildList();
console.log(jsonData); //expecting data from fetch. but returns undefined
function getBuildList(){
fetch('http://127.0.0.1:8000/builds/buildStatsAPI')
.then(function(res){
return res.json();
})
.then(function(data) {
initialLoad(data);
let myData = data;
return myData;
})
.catch(function(err){
console.log(err);
});
}