2

I have past experience with Promises and Fetch calls in JavaScript but I just can't 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.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
tyvm
  • 121
  • 1
  • 11
  • Where is the `data` defined that you are assigning to in `main`, and where are you attempting to use it? – Bergi Aug 11 '23 at 23:00

2 Answers2

0

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();
xdeepakv
  • 7,835
  • 2
  • 22
  • 32
  • Ive noticed that when I call console.log(data) it doesn't tell a true story of when the variable it set. I get a false impression that data is set to a value but when I call it elsewhere I get undefined. – tyvm Mar 28 '20 at 19:42
0

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.

Radu Diță
  • 13,476
  • 2
  • 30
  • 34
  • Hey, thanks for the help but I am still facing the same problem. It feels like I'm just going in circles constantly adding another layer of async/await... console.log(data) prints out the correct data but only at the end of the whole output. By this time the rest of the program has ran with 'data' being undefined... – tyvm Mar 30 '20 at 17:01