Unable to set result of Fetch call to a variable and the Promise doesn't resolve

Viewed 85

I have past experience with Promises and Fetch calls in Javascript but I just cant seem to figure this out.

I am trying to fetch data from a site and store a part of the header as shown below:



async function getData() {

    let response = await fetch("url.....", requestOptions);

    let data = await response.headers.get('set-cookie') 

    return data;
  }

async function main() 
{
    const dataset = await getData();
    console.log(dataset) // This here prints out the data AFTER everything has ran, makes sense as it probably waits for the promise to be resolved.
    data = dataset // This does not set the value of data to dataset. It sets it to Promise <Pending> 
  }

main();


So from here how can I finally set the variable Data to the resolved promise? I thought the 'await getData()' would wait for the promise to be resolved before continuing, thus allowing data to be set to an actual value and not a promise.

2 Answers

This code is working fine for me, Seem issue with console.log

console.log() async or sync?

async function getData() {
  let response = await fetch("http://localhost:8080/");
  let data = await response.headers.get('content-length') 
  return data;
}

async function main() 
{
  const dataset = await getData();
  console.log(dataset) // This here prints out the data AFTER everything has ran, makes sense as it probably waits for the promise to be resolved.
  data = dataset // This does not set the value of data to dataset. It sets it to Promise <Pending> 
  console.log(data)
}

main();

You also need to await main.

I'm guessing you're doing something like this

main() //call to main
console.log(data) //call to see `global` var data set

You need to do something like this

await main()
console.log(data)

If you're calling main from top level, you may not be able to add await so you need to declare an inline async method and call it.

Related