0

I have an object called config that I export it in a ts file. I need to fill config.userServiceUrl with the result of an async request.
myconfig.ts:

export const config = {
   userServiceUrl: "shouldBeResultOfGetAsync",
   someProperty: "someValue"
}

I have a function named GetAsync

  export async function GetAsync(url: string) {
  let response = await fetch(url, {
     method: 'GET',
     headers: {  'Content-Type': 'application/json' },
     body: JSON.stringify(data) 
  });
  let json = await response.json();
  return json;
 }

If I initialize config.userServiceUrl with some dummy value e.g empty string, later I can set that property using .then() method like this:

GetAsync(myUrl).then((result) => { config.userServiceUrl = result; } )

But I need to initialize the userServiceUrl property with the result of async request.

I can access the result of GetAsync method using await keyword. But I couldn't set like this:

export const config = {
       userServiceUrl: await GetAsync(myUrl),
       someProperty: "someValue"
    }

I couldn't comprehend async programming in JS yet, I hope I was able to explain. Many thanks in advance.

happy-integer
  • 383
  • 1
  • 3
  • 15

1 Answers1

0

As Heretic Monkey already mentioned this doesn't work (You just can't access the result of an asynchronous call synchronously: How to return the response from an asynchronous call?).
You should probably initialize it with a dummy value and then set the attribute using another function.

kaffarell
  • 639
  • 5
  • 16