admin管理员组文章数量:1401673
I'm fairly new to service workers and almost every tutorial/article I read uses .then()
since the service worker relay heavily on promises, but I haven't seen any tutorial using async/await when working with service workers. Is there a reason why? are the tutorials old or I just shouldn't use async/await with service workers?
Example:
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);
});
});
}
Could have been done using async/await?
Sources I took a look at that use .then()
I'm fairly new to service workers and almost every tutorial/article I read uses .then()
since the service worker relay heavily on promises, but I haven't seen any tutorial using async/await when working with service workers. Is there a reason why? are the tutorials old or I just shouldn't use async/await with service workers?
Example:
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);
});
});
}
Could have been done using async/await?
Sources I took a look at that use .then()
https://developers.google./web/fundamentals/primers/service-workers/registration
https://developers.google./web/fundamentals/primers/service-workers
https://developers.google./web/fundamentals/primers/service-workers/lifecycle
https://developers.google./web/fundamentals/codelabs/offline
Share Improve this question asked Jan 6, 2020 at 23:14 Patricio VargasPatricio Vargas 5,53214 gold badges55 silver badges107 bronze badges1 Answer
Reset to default 6Promises with then/catch can be used interchangeably with async/await. If you wish, you can replace the then's with awaits and the errors with 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);
}
本文标签: javascriptUsing asyncawait with service workerStack Overflow
版权声明:本文标题:javascript - Using asyncawait with service worker - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744314204a2600181.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论