Can an asynchronous function complete execution in the middle of two synchronous statements?

I am currently developing a script that will fetch a specific resource r from the server upon request using AJAX (asynchronously), and then execute a callback function f with the returned resource.

To optimize performance, I want the script to not make another AJAX call if the requested resource is already being fetched. Instead, it should trigger the callback once the ongoing download of the resource is completed:

JavaScript

var nowLoading = {};

/**
 * @param {String} r - The resource identifier
 * @param {Object} f - Callback function with returned resource
 */
function Load(r, f)
{
    if (nowLoading.hasOwnProperty(r))
    {
        // the requested resource is already loading, so wait for it to finish
        nowLoading[r].OnReady = function () {
            // ...
            f(resource);
        };
    }
    else
    {
        // initiate a new request
        var xhr = XHRFactory.Spawn();
        nowLoading[r] = xhr;

        xhr.OnReady = function () {
            // ...
            f(resource);
        };

        xhr.open('GET', url);
        xhr.send();
    }
};

Is there any chance, however small, that the AJAX call completes between nowLoading.hasOwnProperty(r) and nowLoading[r].OnReady = fn statements?

Or have I misunderstood JavaScript in this context, and can OnReady only occur after all sequential statements are executed?

If the former is true, it could mean that the callback attached to a property of nowLoading may never be called, as OnReady occurred before it was attached.


NOTE: OnReady is a custom case of XHR.onreadystatechange. Additionally, please note that for simplicity, OnReady does not clear the previous handler, but simply adds a new one.

Answer №1

When it comes to Javascript, it operates on a single thread for execution (although there are some engines that attempt to multitask by mimicking a single-threaded appearance).

Regarding your inquiry, since the code is running on a single thread and callbacks are registered to run once the current execution stack is fully unwound, there is no possibility of the code running between statements.

To better understand how Javascript's event loop functions behind the scenes, you can refer to this informative link:

In response to the next part of your query:

It is conceivable that the callback linked to the property of nowLoading may not be executed if OnReady takes place before anything is attached to it.

The nature of Javascript does allow for this scenario if the call completes synchronously. However, in the case of using Ajax as demonstrated here, the call will always be asynchronous, ensuring that the callback gets registered appropriately.

Answer №2

Sorry, it's not possible to execute asynchronous code while synchronous code is running due to a key feature of JavaScript:

"Run-to-completion"

JavaScript processes each message completely before moving on to the next one. This has benefits when understanding how your program runs, such as the guarantee that a function will run entirely without interruption, unlike in languages like C where functions can be paused at any point to allow other code to run.

As a result, asynchronous code will have to wait until all synchronous code has finished executing before it can run.

Answer №3

When dealing with asynchronous functions, it's important to remember that they operate independently from the main thread. In JavaScript, which is typically single-threaded (unless you're utilizing HTML5's Web Workers for true multi-threading), callbacks won't execute until the runtime engine has finished processing other tasks.

Essentially, this means that callbacks cannot interrupt or occur between two synchronous statements in your code. They will only be triggered when the runtime engine is free to do so.

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

Following a POST request, the redirection functionality in Next.js seems to be malfunctioning

I am facing an issue with redirecting the user after submitting a form. I have a button that triggers a post request to my API route, which then inserts a row in the database. The goal is to redirect the user to / once everything is done. However, the retu ...

Can you please explain the meaning of "!" in JavaScript as it pertains to my explanation?

I comprehend how the exclamation mark is used in code such as != or !==, but I am curious about its meaning when it precedes something like if(!arr[i]){"do this} Appreciate your response. ...

Guide to extracting information from a Node.js http get call

I am currently working on a function to handle http get requests, but I keep running into issues where my data seems to disappear. Since I am relatively new to Node.js, I would greatly appreciate any assistance. function fetchData(){ var http = requir ...

The ThreeJS scene may run smoothly at 60 frames per second, but it maxes out my fans and crashes after

Recently, I delved into the world of threeJS and decided to test my skills by using this example: After exporting some terrain from blender and replacing the platform.json file, my scene was running smoothly at 55-60fps. However, as time went on, my compu ...

Safari experiencing issues with Brightcove's chromeless video player controls

There seems to be an issue with BrightCove's Chromeless player. When hovering over the controls (pause, play, and move to a specific time in the video), they appear but clicking on them causes them to just disappear instead of pausing/playing or movi ...

Is there a way to seamlessly roll the camera using a button in ThreeJS alongside TrackballControls without causing any conflicts?

When working with ThreeJS, I encountered an issue with rotating the camera using a button. Here is the code snippet I used: camera = new THREE.PerspectiveCamera(...) function roll(angle) { const quaternion = new THREE.Quaternion(); const lookat = ...

Unable to retrieve data on the frontend using Node.js and React

I have been attempting to retrieve all user data from the backend to display on the webpage. However, it seems that the getAllUsers() function is not returning a response, as no console logs are being displayed. Here is my ViewUsers.js file: import React, ...

Loading dynamic content using AJAX and parsing XML data with simpleXML

I have the code below in my 'update_xml.php' file: $xml = simplexml_load_file('content.xml'); $name = $_POST['name']; $xml->home->main->title = $name; $output = $xml->asXML(); ... Currently, I am utilizing AJAX t ...

Refresh the HTML table following each AJAX request

Each time my AJAX requests are made, new rows keep getting added to my HTML table. I need the table to be updated with fresh data on each call, without appending. This is my current code: var data = $('#data_input').val(); var tableRef = docume ...

Issue with Node.js: Promise not completing execution

My current project involves retrieving data from multiple collections in MongoDB using Node.js and promises. Below is a snippet of the basic code I am using: await Promise.all( ["a", "b", "c"].map(async (collection) =& ...

JavaScript function trying to send a POST request to API

I'm encountering an issue when attempting to execute an API GET request using JavaScript's built-in XMLHttpRequest function. I'm perplexed by why this functionality is failing to operate properly. function getStats(username){ const request ...

Tips for adjusting the number of rows in a textarea using Bootstrap

I currently have a textarea in my project that allows users to input text using Bootstrap. However, the height of the textarea is fixed at 3 rows by default. I want to make it dynamic so that as the user types beyond 3 rows, the textarea expands instead of ...

Showing information from a database query

Let's say we have a form that submits data to the dataprocess.php file after submission. The dataprocess.php file processes the form variables and outputs the desired results. It can be challenging to directly echo content into a specific div on a pa ...

"Uncaught ReferenceError: Rawdata.some is not defined, and a table design

Currently, I am in the process of developing a basic table using data retrieved from the backend via an API call with Ant Design in React. The version of Ant Design I am using is: "antd": "^5.1.1", My approach involves making an API ...

Only collapsing the uppermost level in the CSS hierarchy

Within my template, I have utilized the same tree structure code that was referenced in a previous question found at this link. The solution provided in that question initializes the page with the entire tree collapsed (view jsfiddle). My goal is to modif ...

Managed/Voluntary Input

Why is React showing an issue with controlled/uncontrolled input? The initial state of value is set to this.state.text, which starts as an empty string in the constructor. import React from 'react'; class MyComponent extends React.Component { ...

Tips for setting up the image as the header background in HTML5 and CSS3

I am currently designing a website. I'm wondering if there is a way to create a div with a curved bottom using HTML5, CSS3 and JavaScript. It should resemble the design of the curved header bottom ...

Troubleshooting issue: AngularJS nested views are not being displayed while utilizing the angular route

I am currently implementing nested views within a mobile application. In my attempts to incorporate this functionality, I came across the following module: However, despite observing the templates being loaded via XHR, nothing is displayed on the page. I ...

Tips for altering the appearance of a header when clicked on?

I am trying to change the internal style sheet in the "style" head when a user clicks, without using inline styles. I have successfully added new CSS for divone as text, but I can't seem to delete the old one (element.classList.remove("#divone");). Is ...

The linking process in AngularJS is encountering difficulties when trying to interact with

I've already looked at similar questions, and my code seems correct based on the answers provided. It's a very simple beginner code. <html ng-app=""> <head> <title>Assignment</title> <script src=" ...