J Doe
J Doe

Reputation: 41

Why isn't await working with async on firefox

basically i have this function

async function get(url){
  const response = await fetch(url);
  const resData = await response.text();
  return resData;
}

then later i have this call

let data = await get(am_url);

the code works perfectly on google chrome, but on firefox, i get this error on the call line :

SyntaxError: await is only valid in async functions and async generators

what's the problem here, for the life of me, i can't seem to make this work on firefox and can't figure out why

for example if i open google.com on firefox and google chrome, then i go to the console, and pase this code, on chrome, it will run, but on firefox, it will throw the error i mentionned

async function get(url){
  const response = await fetch(url);
  const resData = await response.text();
  return resData;
}

let data = await get("http://google.com");
console.log(data)

Upvotes: 3

Views: 4858

Answers (3)

fregante
fregante

Reputation: 31698

As the error suggests, await only works inside async functions. Normally you can't use await like that, but you have to create an async function first or use .then() instead of await.

However there are 2 things to be aware of:

  1. The console supports await outside an async function just to simplify your life. Chrome did it first, then Firefox more recently. Your example now works in both browsers.
  2. In a future version of ECMAScript, you will be able to use await outside async functions, it's called "top-level await", so that code will soon work everywhere (in a type="module" context)

Upvotes: 1

dcorking
dcorking

Reputation: 1206

In 2018 when this question was asked, most JavaScript consoles did not await at the top level.

At that time, Google Chrome Developer Tools console was the exception. They added the feature in late 2017 in Chrome 62

This is why, in the Firefox version you used when you asked this question, you have to resolve the promise, for example with then/catch.

If you update to a current Firefox, such as version 72 (early 2020), the code in your question will work. As fregante pointed out in a comment, in 2019, Firefox upgraded their console to support top level await.

Upvotes: 0

Sumer
Sumer

Reputation: 2867

In main either put your below code in self executing async function or use .then.

let data = await get(am_url);

should be changed to

(async()=>{ let data = await get(am_url) })()

or

get(am_url).then( data => ....)

Upvotes: 5

Related Questions