HTML and CSS Reference
In-Depth Information
For complex processing that requires several database calls, you'll need to be careful to nest the event
handlers and consider when they are executed. For example, if you needed to make three database requests, your
code might look like this:
var request = dbCall1()
request.onsuccess = function (e1) {
dbCall2().onsuccess = function (e2) {
dbCall3().onsuccess = function (e3) {
request.onerror = function(e) {
alert("The call failed")
This code calls dbCall1() , dbCall2 (), and dbCall3 (), in that order and they will be processed sequentially.
In other words, dbCall2() will not start until dbCall1() has completed, and only if it was successful. Each call
provides an onsuccess event handler, which makes the next call. If the first call fails, an alert is raised. What may
be unexpected is the order that the non-database calls are executed. The database calls return immediately and
the event handler is called later, when the operation has completed. As soon as the call to dbCall2() is made, the
function returns and f2() will be executed. Then later, the dbCall2() completes, its event handler is called and
f3() is executed.
Because of the nesting approach, the event handler has access to the event object from previous calls. For
this reason, you should use unique names for the event parameter. This will avoid ambiguity. Also, notice the
use of closure to access these event objects. As I mentioned, f2() is called before f3() so the event handler
for dbCall1() which defines the e1 parameter, has completed and is no longer in scope by the time the event
handler for dbCall2() is executed. The closure feature of JavaScript allows the subsequent event handlers
to access this object. This is important because if you need to access all three object stores to complete an
operation, you will need to wait until all three have completed and then access all three results.
To avoid closure, you could extract the properties that you need from the first two database calls and store
them in local variables (declared prior to the dbCall1() call. Then in the f5() call you can use these variables
instead of the e1 and e2 event objects. This is just a matter of preference, as either approach will work fine.
Using Transactions
All data access, both reading and writing, is done within a transaction, so you must first create a transaction
object. When the transaction is created you specify its scope, which is defined by the object stores it will access.
Search WWH ::

Custom Search