问题
For my IndexedDB I'm pulling various Ajax requests that will provide the data to the objectStores. Since transactions are asynchronous how should I chain the creation of the objectStores? I'm thinking in doing it like this:
1- Pull all the Ajax requests in the beginning of the script.
2- Request to open the DB.
3- In the onsuccess handler open the first transaction to create the first objectStore and insert the respective data.
4- Call the oncomplete event on the first transaction to create a second transaction.
5- Do this for all the objectStores that need to be created.
Is this the best way, or should I just write all the transactions inside the onsuccess handler of the indexedDB.open request?
Can I create various objectStores and insert large amounts of data at the same time without causing errors?
回答1:
You can do everything in one transaction. If you open your transaction, you define the scope of this transaction. The scope can exist out of multiple object stores. By providing an array of all the names of the object stores you want to target.
var transaction = db.transaction(["obj1", "obj2"]);
回答2:
In my experience transactions tend to close when waiting for an AJAX response so you have to open the transaction in the success handler for the AJAX response.
There is definitely nothing wrong with having multiple, overlapping transactions "running" in parallel, but in practice JavaScript is still single-threaded - you'll find that even the AJAX success handlers run sequentially and ordering is fairly predictable (though not guaranteed), so if you open a transaction in each, and then process the data with a series of puts, what you may actually see is:
openAjax1()
openAjax2()
ajax1Complete()
// in here, open transaction1 and call objectStore1.put() many times
ajax2Complete()
// in here, open transaction2 and call objectStore2.put() many times
put() // from ajax1
put() // from ajax1
put() // from ajax1
... // from ajax1
// transaction1 completes
put() // from ajax2
put() // from ajax2
put() // from ajax2
... // from ajax2
// transaction2 completes
In theory, the only way to actually make things happen in parallel is to use worker threads, but even then most implementations will funnel the work down to a single thread. In practice, the backends are pretty good about optimizing "bulk" writes together so you wouldn't even get much of a performance improvement from using workers.
来源:https://stackoverflow.com/questions/12638253/what-is-the-best-way-to-create-various-indexeddb-objectstores-within-the-same-sc