I am retrieving a value with fetch and need to assign it to an object's property right away. My fetch call is working in the sense that I am getting the value I expect to, but I'm not handling the Promises properly, so the value is still undefined whenever I go to consume it. There are many questions like this online but I've tried tons of variations on this and I just can't get it to work. I am running this in the top level of a .js file, but I can't seem to get top-level async-await to work either. Here's what I'm trying, where is this going wrong?
const query_url = 'the request url is correct'
function fetchValues(url) {
return fetch(url)
.then(resp => resp.json())
.then(_values => {return _values})
.catch(err => console.log({'Error getting values': err}))
}
_object.neededValue = fetchValues(query_url).neededValue
// Next, use _object right away such that _object.neededValue must be assigned
I thought this blog post would be helpful since it executes similar code, but I couldn't get any use of async/await to work as expected. https://dev.to/ramonak/javascript-how-to-access-the-return-value-of-a-promise-object-1bck