I'm struggling with fetch()
, which I'm using to retrieve JSON. I think the problem is that the code completes and tries to 'act' on the array before fetch()
has actually downloaded and processed it. I wrote a simpler version initially, which resulted in the same problem; most of the code here is from Google Developers.
As shown below (setTimeout only included to demonstrate the problem) I get different results when accessing the same array twice, a second apart:
dataResultArray = requestJSONResult(searchString);
console.log(dataResultArray); // logs '[]'
console.log(dataResultArray.length); // logs '0'
setTimeout(function(){
console.log(dataResultArray); // logs the actual JSON array contents
console.log(dataResultArray.length); // logs the real array length
}, 1000);
function requestJSONResult(searchString) {
var tempArray = []
fetch(`/search/?term=${searchString}`)
.then(status)
.then(json)
.then(function(data) {
tempArray.push(...data)
}).catch(function(error) {
console.log('Request failed', error);
});
return tempArray;
}
function status(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()
}