DEV Community

Discussion on: JS Async: async/await

Collapse
 
felipesousa profile image
Felipe Sousa

In this case, await can only be used within functions declared with the “async” keyword, using await in global scope or outside a function with “async” triggers the following error:

const myPromise = new Promise((resolve) => {
  resolve(payload)
});

const response = await myPromise; // SyntaxError: await is only valid in async function

😁

Collapse
 
mellen profile image
Matt Ellen • Edited

That's interesting. In the console (Firefox) it worked fine. I guess that's a different scope again.

const resp = await fetch('https://dev.to');
const text = await resp.text();
console.log(text);
Thread Thread
 
felipesousa profile image
Felipe Sousa

I really believe that it is something related to the scope within the browser. Anyway, there is a proposal to implement “await” in the global scope: ECMAScript proposal: Top-level await, currently in phase 3, but it contains some interesting discussions about this implementation: Top-level await is a footgun 👣🔫.