与服务工作者一起使用异步/等待

devpato

对于服务人员,我是相当陌生的人,几乎我阅读的每一篇教程/文章都使用它,.then()因为服务人员在很大程度上兑现了Promise,但在与服务人员合作时,我还没有看到任何使用异步/等待的教程。有什么理由吗?教程太旧了,还是我不应该对服务人员使用异步/等待?

例:

if ('serviceWorker' in navigator) {
  window.addEventListener('load', function() {
    navigator.serviceWorker.register('/sw.js').then(function(registration) {
      // Registration was successful
      console.log('ServiceWorker registration successful with scope: ', registration.scope);
    }, function(err) {
      // registration failed :(
      console.log('ServiceWorker registration failed: ', err);
    });
  });
}

可以使用async / await完成吗?

我看过的资料来源 .then()

https://developers.google.com/web/fundamentals/primers/service-workers/registration

https://developers.google.com/web/fundamentals/primers/service-workers

https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle

https://developers.google.com/web/fundamentals/codelabs/offline

名称

then / catch的承诺可以与async / await互换使用。如果愿意,可以将a替换为awaits,将错误替换为catchs ...

// inside an async function
// assuming that register() is a promise-returning function...
try {
  let registration = await navigator.serviceWorker.register('/sw.js')
  console.log('ServiceWorker registration successful with scope: ', registration.scope);
} catch(err) {
  console.log('ServiceWorker registration failed: ', err);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章