0

How can I set window variables from inner side of async self excuting function. When I use await just before fetch, I get "error: Uncaught ReferenceError: bar is not defined". When I removed the await, in that case, I get the Promise object.

(async function (w){

    bar = await fetch('https://jsonplaceholder.typicode.com/posts').then(()=>{
      response.json()
    }).then((data)=>{
      return data
    });

    w.bar=bar;

 })(window); 

 console.log(bar);
Erdal76t
  • 113
  • 1
  • 9
  • because it's async function – apple apple Jan 12 '21 at 14:03
  • You're assigning to the global variable just fine. Put it's pointless, as the code outside of the async IIFE does not wait until the variable is assigned. So don't make it global, and put the `console.log` *inside* the async function, after the `await`. – Bergi Jan 12 '21 at 14:29

1 Answers1

1

The error: Uncaught ReferenceError: bar is not defined is being throw at the time you try to log bar console.log(bar);

This cannot work since your are waiting for the fetch to complete using await keyword, so the when this line console.log(bar); is reach your variable bar is not defiend because the fetch() did not finish yet and this line w.bar=bar; was not called yet.

If you need to use the result of your fetch outside of the function, remove await keyword and whereever you need to use the the result wait for the promise to complete, for example to log it: bar.then(data => console.log(data))

Dahou
  • 522
  • 4
  • 12