0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

waitUntilの対象をasync functionで書く

Posted at

小ネタですが、見事にはまり込んでしまったので書いていきます.

waitUntilとは

Service Workerを使うと「インストール」というプロセスが発生しますが、Service Worker内で行う処理はキャッシュ処理、fetchによる通信など、非同期なもので溢れています。

そこで、イベントオブジェクトにwaitUntil()というメソッドが生えていて、このwaitUntilPromiseを渡せば、Promiseが完結したところでインストール完了となる(Promiseが失敗すればインストール失敗となる)、というものとなっています。

やらかしたパターン

多くの場合、キャッシュを開くcaches.open().then()から始めて自然とPromiseを渡すようにできるのですが、ある時この処理をasync functionで書こうとしました。

失敗作.js
addEventListener('install', e => {
  e.waitUntil(async () => {
    const cache = await caches.open(CACHE_NAME);
    // 後略
  });
});

こうしてみたところ、引数の関数には入ることもなく処理が進んでしまいました。

冷静に考えれば

よくよく考えれば、上に書いたように、waitUntil()が取るものはPromiseであって、関数ではありませんでした。ということで、その場でasync functionを実行してPromiseを得ておきましょう。

修正版.js
addEventListener('install', e => {
  e.waitUntil((async () => {
    const cache = await caches.open(CACHE_NAME);
    // 後略
  })());
});
0
2
0

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
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?