0

In many js examples, I see calls to functions doing tasks asynchronous, for example:

var objectStoreTitleRequest = objectStore.get(title);

objectStoreTitleRequest.onsuccess = function() {
 // Grab the data object returned as the result
 var data = objectStoreTitleRequest.result;
}

(This example is based on https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest/onsuccess)

I wonder how this could work if the async execution finished before the onsuccess handler is set. I expected that event handlers added before execution of the async function, but all js examples add handlers after the call (in this case: get()). How is this internally solved? And how can I implement a custom object which provides a similar API? I think this must be something like

 {self.result = do_work(); wait for onsuccess handler is set...; if handler_avail -> self.onsuccess(); }
cytrinox
  • 1,846
  • 5
  • 25
  • 46

2 Answers2

0

Because Javascript is strictly single-threaded, asynchronous operations can only run their callbacks once other code has finished running.

Therefore, it is impossible for the request to finish between two lines.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/get [...]The get() method of the IDBObjectStore interface returns an IDBRequest object, and, in a separate thread, returns the object store selected by the specified key.[...] If it is strictly single threaded, why they introduce threads at this point? – cytrinox Feb 21 '16 at 21:46
  • That documentation is poorly written; they actually mean asynchronously. (the implementation is a native C code in a separate thread, but that isn't relevant) – SLaks Feb 21 '16 at 21:53
  • Can you provide an example how to write a async function which calls a onsuccess handler (if set)? I don't understand why it's named asynchronous if the following code still waits for the async execution. – cytrinox Feb 21 '16 at 22:03
0

This is exactly the reason why you should never call a callback function / event handler synchronously.

For example, the following code is wrong:

function async(val, cb) {
  if(val < 0) {
    cb();
  }
  else {
    setTimeout(cb, val);
  }
}

And must instead be implemented similar to:

function async(val, cb) {
  if(val < 0) {
    setTimeout(cb, 0);
  }
  else {
    setTimeout(cb, val);
  }
}
Amit
  • 45,440
  • 9
  • 78
  • 110