LoginSignup
2
1

More than 1 year has passed since last update.

【JavaScript / jQuery / 非同期処理】「$(async function() {...})」と書いて良いのは jQuery 3.3系 以降っぽい

Last updated at Posted at 2021-07-29

前段

$(function() {...})内で、ある非同期処理を await で待機する処理を書こうとしてハマった話です。

結論

$(async function() {...})と書いて良いのは jQuery 3.3系以降のようです。

それ以前のバージョンの jQuery を使用しているなら
document.addEventListener('DOMContentLoaded', async function() {...}
で代替するしかなさそうです。

内容

await を記述するために$(async function() {...}と書いたのですが、実行させるとそもそもこの関数自体が実行されなくなってしまいました。

もちろん、以下のように await を直接書いてしまうとUncaught SyntaxError: await is only valid in async functions and the top level bodies of modulesのエラーが発生します。

function resolveAfter2Seconds() {
    return new Promise(resolve => {
      setTimeout(() => {
        resolve('resolved');
      }, 2000);
    });
  }

$(function() {
    const result = await resolveAfter2Seconds();
    console.log(result);
});

調べると、$(async function() {...}を認識してくれるのは jQuery 3.3系以降のようでした。

Google Hosted Libraries で1つずつ確認しました。(3.3.0 はCDNに存在しなかったようなので未調査)

バージョン 結果
1.X系
2.X系
3.2.0
3.3.1
3.4.0

jQuery 3.X 系のバージョンアップ情報を探しても正確な情報は見つけられなかったのですが、
実際に src のバージョンを書き換えて1つずつ実行してみた結果が前述の表になります。

@ko1nksm さんより情報頂きました。ありがとうございます
https://qiita.com/shimamura_io/items/57e18f11d3cc0faaefce#comment-80979316e737ee64bef8

2
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1