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);
The
error: Uncaught ReferenceError: bar is not definedis being throw at the time you try to logbarconsole.log(bar);This cannot work since your are waiting for the fetch to complete using
awaitkeyword, so the when this lineconsole.log(bar);is reach your variablebaris not defiend because thefetch()did not finish yet and this linew.bar=bar;was not called yet.If you need to use the result of your fetch outside of the function, remove
awaitkeyword 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))