0

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

Alex
  • 2,154
  • 3
  • 26
  • 49
  • 1
    The value won't exist until the HTTP request has had a response. You can't have it yet. The promise is a promise that it will exist in the future. – Quentin Apr 15 '21 at 16:33
  • 1
    What you are trying is impossible. With top level await you are on the right track, though it is not quite supported everywhere – Jonas Wilms Apr 15 '21 at 16:33
  • 1
    Top level await is a *proposed* feature for ECMAScript. It isn't widely supported yet. – Quentin Apr 15 '21 at 16:34
  • Node supports it since 14.3.0, Deno supports it natively... that's about it – Jeremy Thille Apr 15 '21 at 16:38

0 Answers0