dev*_*ato 5 javascript service-worker progressive-web-apps
我对服务工作者相当.then()陌生,而且我读过的几乎所有教程/文章都使用过,因为服务工作者大量依赖承诺,但我没有看到任何在与服务工作者合作时使用 async/await 的教程。有什么原因吗?教程是旧的还是我不应该对服务工作者使用异步/等待?
例子:
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);
});
});
}
Run Code Online (Sandbox Code Playgroud)
可以使用 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 的 Promise 可以与 async/await 互换使用。如果你愿意,你可以用 awaits 替换 then 和用 catches 替换错误......
// 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);
}
Run Code Online (Sandbox Code Playgroud)