在ServiceWorker中访问indexedDB。比赛条件 [英] Accessing indexedDB in ServiceWorker. Race condition

查看:271
本文介绍了在ServiceWorker中访问indexedDB。比赛条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ServiceWorker中展示indexedDB的示例并不多,但我看到的结构都是这样的:

There aren't many examples demonstrating indexedDB in a ServiceWorker yet, but the ones I saw were all structured like this:

const request = indexedDB.open( 'myDB', 1 );
var db;

request.onupgradeneeded = ...

request.onsuccess = function() {
    db = this.result; // Average 8ms
};


self.onfetch = function(e)
{
    const requestURL = new URL( e.request.url ),
    path = requestURL.pathname;

    if( path === '/test' )
    {
        const response = new Promise( function( resolve )
        {
            console.log( performance.now(), typeof db ); // Average 15ms

            db.transaction( 'cache' ).objectStore( 'cache' ).get( 'test' ).onsuccess = function()
            {
                resolve( new Response( this.result, { headers: { 'content-type':'text/plain' } } ) );
            }
        });

        e.respondWith( response );
    }
}

当ServiceWorker启动时,这可能会失败,如果是这样,什么是在ServiceWorker中访问indexedDB的强大方法?

Is this likely to fail when the ServiceWorker starts up, and if so what is a robust way of accessing indexedDB in a ServiceWorker?

推荐答案

每次ServiceWorker启动时打开IDB是不太可能是最佳的,即使不使用它,你最终也会打开它。而是在需要时打开数据库。单例在这里非常有用(参见 https:/ /github.com/jakearchibald/svgomg/blob/master/src/js/utils/storage.js#L5 ),因此如果IDB在其生命周期内使用了两次,则无需再打开IDB。

Opening the IDB every time the ServiceWorker starts up is unlikely to be optimal, you'll end up opening it even when it isn't used. Instead, open the db when you need it. A singleton is really useful here (see https://github.com/jakearchibald/svgomg/blob/master/src/js/utils/storage.js#L5), so you don't need to open IDB twice if it's used twice in its lifetime.

激活事件是打开IDB并让任何onupdateneeded事件运行的好地方,因为旧版本的ServiceWorker已经不在了。

The "activate" event is a great place to open IDB and let any "onupdateneeded" events run, as the old version of ServiceWorker is out of the way.

这篇关于在ServiceWorker中访问indexedDB。比赛条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆