I have been looking for a way to figure this problem out and apologize if my searching skills are not up to par.
My Issue: I am fetching an API and I want to know when all of the data has been fully loaded. Reading through the docs, it appears that I can chain .then statements with fetch and I thought that would work. But, it appears that they all seem to fire at the same time without waiting for the previous .then to finish.
Here's my code:
fetch(myUrl, {
method: 'post',
headers: {
'Content-Type': 'application/json; charset=utf-8',
},
credentials: 'include',
body: data
})
.then(fetchStatus)
.then(json)
.then(function(msg){
showSearchResults();
setTimeout(function(){ console.log("Next then should fire after this"); }, 4000);
})
.then(function(){
return console.log("The 2nd is firing!");
});
function fetchStatus(response) {
if (response.status >= 200 && response.status < 300) {
return Promise.resolve(response)
} else {
return Promise.reject(new Error(response.statusText))
}
}
function json(response) {
return response.json()
}
This is great if it is asynchronous, but these events need to be synchronous due to the fact that I am trying to work with content that is created by the previous call, showSearchResults();
Any help is much appreciated.