Accessing IndexedDB from multiple javascript threads

前端 未结 3 973
春和景丽
春和景丽 2021-02-03 09:56

Overview: I am trying to avoid a race condition with accessing an IndexedDB from both a webpage and a web-worker.

Setup: Webpage tha

3条回答
  •  长发绾君心
    2021-02-03 10:45

    I think I found a work around for this for now. Not really as clean as I would like, but it seems to be thread safe.

    I start by storing the datetime into a LastEdit field, whenever I update the data. From the web-worker, I am posting a message to the browser.

    self.postMessage('UpdateDataSent#' + data.ID + '#' + data.LastEdit);
    

    Then in the browser I am updating my sent flag, as long as the last edit date hasn't changed.

    // Get the data from the DB in a transaction
    if (data.LastEdit == lastEdit)
    {
        data.Sent = true;
        var saveStore = trans.objectStore("Data");
        var saveRequest = saveStore.put(data);
        console.log('Data updated to Sent');
    }
    

    Since this is all done in a transaction in the browser side, it seems to work fine. Once the browsers support the Sync API I can throw it all away anyway.

提交回复
热议问题