javascript エラー「Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules」の解決方法

javascript エラー「Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules」の解決方法

javascriptで、エラー「Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules」が発生した場合の原因と解決方法を記述してます。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 106.0.5249.103

エラー内容

以下のコードを実行時に発生。

const time = hoge => new Promise(resolve => setTimeout(() => resolve(), hoge))

function foo() {
  console.log(1);
  await time(5000);
  console.log(6);
  
}

foo()

エラーメッセージ

Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules

画像

firefox(バージョン105)では、下記のエラーとなります。

Uncaught SyntaxError: await is only valid in async functions, async generators and modules

画像

safari15.0では、下記のエラーとなります。

SyntaxError: Unexpected identifier 'time'

画像

原因

asyncがないのに、awaitを使用しているため。

解決方法

asyncをちゃんと付けてあげる。

const time = hoge => new Promise(resolve => setTimeout(() => resolve(), hoge))

async function foo() {
  console.log(1);
  await time(5000);
  console.log(6);
  
}

foo()

実行結果

ちなみに、asyncをアロー関数で記述すると以下となります。

const time = hoge => new Promise(resolve => setTimeout(() => resolve(), hoge))

const foo = async () => {
  console.log(1);
  await time(5000);
  console.log(6);
  
}

foo()