parcel-bundler / parcel

The zero configuration build tool for the web. 📦🚀
https://parceljs.org
MIT License
43.47k stars 2.27k forks source link

How to use async/await with parcel? #5176

Closed hxse closed 4 years ago

hxse commented 4 years ago

💬 RFC

🔦 Context

When i run the following example code with parcel index.html, I get a error Uncaught ReferenceError: await is not defined. But, When I copy the script and run it in the Chrome DevTools, it run normally. What are the solutions?

💻 Examples

<body>
    <script>
        async function get(value) {
            let response = await value;
            return await response;
        }
        data = await get('test');
        console.log(data);
    </script>
</body>
kalaschnik commented 4 years ago

You cannot use await outside of async, at least not now (https://github.com/tc39/proposal-top-level-await).

mischnic commented 4 years ago

Correct. The DevTools console essentially already supports top level await.

Related: https://github.com/parcel-bundler/parcel/issues/4028

kalaschnik commented 4 years ago

Thanks mischnic! I was not aware of this. Yet it does not work when I’m on GitHub.com and try to:

let response = await fetch("https://api.chucknorris.io/jokes/random");
let data = await response.json()
data.value

Yet, it works if I’m on the API’s page. Anyway thanks!

mischnic commented 4 years ago

Refused to connect to 'https://api.chucknorris.io/jokes/random' because it violates the following Content Security Policy directive

GIthub sends some headers that block connecting (fetching) from non-whitelisted domains: Content-Security-Policy: ...., connect-src 'self' uploads.github.com www.githubstatus.com ...

kalaschnik commented 4 years ago

Oh true, @mischnic, it indeed works fine on other sites.

Download commented 8 months ago

Arriving on this closed issue today. Getting the same error as OP. But top-level await has been supported for some time in Node JS / Browsers...