Search code examples
javascriptnode.jsasync-awaitself-executing-function

How to reach global window variables from async self executing functions


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);

Solution

  • 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))