How is it that deferred callbacks in JavaScript do not lead to race conditions?

I came across this snippet from the IndexedDB documentation and wanted to write something similar:

var req;
var store = getStore();
req = store.count();
req.onsuccess = function(evt) {
  console.log("success: " + evt.result);
};
req.onerror = function(evt) {
  console.error("add error", this.error);
};

https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB

This made me curious about why JavaScript allows for the definition of callbacks after a call and how it prevents race conditions. Can someone shed some light on this?

How does JavaScript ensure that an async call is not executed before the callback is assigned?

Thank you!

Answer №1

JavaScript operates on a single thread, meaning the sequence of execution for your current code is as outlined below:

store.count();              // initiates some asynchronous operations
req.onsuccess; req.onerror;  // attaches the callback functions
                            // additional code within the same function/scope may be executed

                            // once your code finishes, the next item in the event queue is processed

store.count();              // executes the asynchronous part
req.onsuccess();            // triggers the callback function after the async operation completes

Hence, the timing of attaching callbacks isn't crucial as long as they are linked before the current function concludes and the JavaScript event queue moves on to the next task.


Regarding your statement: In modern JS engines, parsing and execution times differ. The engine compiles the code before running it (with rare instances where an old interpreter-style fallback is utilized, typically not applicable in most scenarios).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are the steps to position the cursor at the end of a WYMeditor box and place focus on it?

On my forum, I am using WYMEditor which allows users to "quote" messages from others. However, when a quote is inserted into the input box, it often takes up more space than the box itself causing messy messages. I want to automatically scroll the content ...

How can React and Redux ensure that response data is accessible to every component?

When using react and redux, how can data written in the useDispatch function be made available in other components? Additionally, how can the customerId be accessed in all components? I have created a code that calls an API and returns data in response. I ...

Is there a way to improve efficiency in JavaScript and JSON by reducing the size of the array?

My partner and I are currently collaborating on the development of a small web application. This app serves as an information hub, sourcing data from a JSON file that is expected to contain around 150 items, each with approximately 130 properties. As we c ...

Conceal Backup Image for Computer Viewing

I am currently working on a project for this website and have added an mp4 video as the background. However, I have run into an issue where the video does not play on mobile devices, so I have had to implement a Fallback Image. The problem is that upon l ...

Only one active class is allowed in the Bootstrap Accordion at any given time

I have implemented Bootstrap's accordion on my webpage, consisting of two different sections with unique content. Upon loading the page, the active class defaults to the first element of the first section. However, if I navigate to the "Second" sectio ...

Retrieve data from a form on the server side using an Ajax request

I am currently working on submitting form data through an Ajax call. Here is the relevant form code: <form target="_blank" id="addCaseForm" class="form-horizontal col-md-12" action="" method="POST> <div class="form-group"> <labe ...

The HierarchyRequestError in Javascript related to XML

var xmlRoot = "<root></root>"; var firstChildNode = "<firstChild></firstChild>"; var parser = new DOMParser(); var xmlDom = parse.parseFromString(xmlRoot, "text/xml"); var xmlChildNode = parse.parseFromString(firstChildNode, "text/ ...

What is the best way to eliminate specific duplicate characters from a string using JavaScript?

I have a project involving managing email responses, where the reply function includes pre-written content like Re: ${Subject of the email} The issue I'm facing is that after the 2nd reply, there is a repeated Re: , so I created a function to remove ...

Arrange by alphabetical order using a dropdown menu

I am stuck and need some help! I have a working Itemlist with Angular, but now I want to add sorting by a select-box. It should look something like this: preview Here is a Plunker example: https://embed.plnkr.co/JYF0u9jBbsfyIlraH3BJ/ <div id="ideaLis ...

"Enhance your calculator experience with three text fields, utilizing jQuery to allow writing in only one field at

I have a question regarding my calculator in Jquery. It has 3 different text fields and when I use the number buttons, it writes in all three fields simultaneously because of using $("input[type=text]") in the input declaration. I want to change this beh ...

What is the best way to incorporate Vue.js component dependencies into a multi-page application (MPA

When working with a multiple page app, incorporating a component inside another component can be challenging, especially without using a build system. $ npm install sagalbot/vue-select <template> <div id="myApp"> <v-select :value.sy ...

Disabling a button in Jquery during a synchronous request

Struggling to deactivate a button to prevent multiple clicks during a synchronous ajax call. My current code looks like this. <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <link type="text/css" rel="stylesheet" href=" ...

Adjusting a data point as v-model is updated

I'm working on a text input that is using the v-model to bind its value to data. I also need to trigger my parse() function whenever the value of this v-model changes, so that I can update an array within the data object. <div id="app"> < ...

Locate a specific tag within an XML document using user input and then showcase the content that is encapsulated by it utilizing Node

Could someone kindly advise on how to locate a tag name within an XML dom based on user input and then iterate through and display all content within it? For example, if the user enters 'unit', the program should display everything within the uni ...

Modified the object path and updated the Dirty stages for nested objects within Vue state

Imagine having an object that contains arrays of objects in some properties. Whenever changes are made to any field, whether it's within an object in an array or the main object itself, you want to mark that object as "dirty" using a code snippet like ...

Angular - Dividing Functionality into Multiple Modules

I am currently working with two separate modules that have completely different designs. To integrate these modules, I decided to create a new module called "accounts". However, when I include the line import { AppComponent as Account_AppComponent} from &a ...

ngMaterial flex layout not functioning properly

I can't seem to figure out why ngMaterial is not laying out my simple hello world app in a row. Despite checking the console for errors, I still can't see what I am doing wrong. I expected the content below to be displayed horizontally instead of ...

Performance issues may arise in React styled-components when the state changes frequently during mousemove events

My current challenge involves implementing a parallax animation using react hooks and styled-components, but I am facing performance issues. The constant rerenders of components seem to be causing janky animations rather than smooth ones. Here are the sty ...

Enhancing material appearance by incorporating color gradient through the extension of three.js Material class using the onBeforeCompile method

In my three.js scene, I have successfully loaded an .obj file using THREE.OBJLoader. Now, I am looking to add a linear color gradient along the z-axis to this object while keeping the MeshStandardMaterial shaders intact. Below is an example of a 2-color l ...

Displaying the getJSON output only once, then having it automatically update at regular intervals without any repetitive results

I previously had an issue resolved on stackoverflow, but the requirements of my project have changed. Therefore, I am in need of a new solution. In summary, I have a getJSON function that runs every 5 seconds to check for changes in a JSON file. The proble ...