Accessing IndexedDB from multiple javascript threads

前端 未结 3 964
春和景丽
春和景丽 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:33

    Can you use a transaction?
    https://developer.mozilla.org/en/IndexedDB/IDBTransaction

    0 讨论(0)
  • 2021-02-03 10:38

    Old thread but the use of a transaction would solve the Failed Solution approach. I.e. the transaction only needs to span the check that the data in the IndexedDB hasn't change after the send and marking it as sent if there was no change. If there was a change, the transaction ends without writing.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题