Could it be feasible to manage several ongoing asynchronous requests simultaneously?

Visualize a grid in which the user completes cell A1 and presses Enter to move to A2. As this happens, a request is sent to the backend to search a database and retrieve results for populating the remaining cells in row A. Meanwhile, I want the user to continue typing in cells A2, A3, and so on.
Now, the questions are:

  • Is it possible to have multiple ongoing asynchronous requests firing sequentially without one cancelling out the previous one before its results are achieved?
  • The database being accessed is a corporate data warehouse known for being slow. Is there a maximum duration that an async request can remain "open"? Will browsers time out?
  • If I send out async requests #1, #2, and #3, but they are received in the order of #2, #3, #1 - what implications does this have?

Thank you.

Answer №1

Addressing your inquiries one by one:

  1. Absolutely, it is possible to have multiple HTTP requests concurrently. Take the scenario of loading a webpage for instance. Numerous requests are made to different sources simultaneously. As these requests are fulfilled, the corresponding callback functions update the content on the page.

  2. Indeed, they will. A request will inevitably time out after a certain period. Each browser has its own predefined duration for keeping a request open. Once this time limit is reached, the request is terminated.

  3. The sequence in which the requests are resolved does not matter. You'll be utilizing a callback-based approach to handle the HTTP response. Each callback function pertains to a specific request and should manage itself accordingly.

Answer №2

Is it possible to have multiple asynchronous requests firing sequentially even before the results of previous requests are resolved?

Indeed.

Does each subsequent async request cancel out the preceding one?

No, they do not.

The database I'm accessing is a corporate data warehouse, which might be very slow. Is there a limit to how long an async request can remain "open"? Do browsers eventually time out?

Yes, async requests will ultimately time out. (However, assuming a corporate data warehouse's database is inherently sluggish may not be accurate.)

Suppose I send out async requests #1, #2, and #3, but receive responses in the order #2, #3, #1 - does this have any consequences?

Most APIs like XMLHttpRequest, fetch, etc., handle completion callbacks based on when operations complete, not necessarily in the order they started. This discrepancy could indeed lead to issues if your code isn't prepared for it.


For instance, this snippet on jsFiddle demonstrates three concurrent asynchronous requests completing in different orders:

function doRequest(reqnum, reqdata) {
    const delay = (1000 + Math.floor(Math.random() * 3000)) / 1000;
    const json = JSON.stringify({data: reqdata});
    return fetch("/echo/json/", {
        method: "POST",
        body: `delay=${delay}&json=${encodeURIComponent(json)}`
    })
    .then(res => {
        if (!res.ok) {
            throw new Error("HTTP status " + res.status);
        }
        return res.json();
    })
    .then(data => {
        console.log(`${reqnum} complete, data = ${data.data}`);
    });
}

doRequest(1, "one");
doRequest(2, "two");
doRequest(3, "three");

Live Example

Answer №3

Avoid the misconception that JavaScript is always single-threaded – multiple outstanding async requests are possible. This scenario often arises when implementing sleep functions.

function snooze(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

Put the snooze function to the test by calling it multiple times before the initial request resolves. Remember to declare your functions as async.

Take caution against the hangover error. Initiating a function more than once will not cancel the previous request. To see this concept in action, check out this working example: https://codepen.io/anon/pen/Jmpcq/?editors=101

An eventual timeout is bound to happen.

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

When trying to access the same path, useEffect does not trigger

I integrated the API to execute when the screen is loaded using useEffect in Next.js v10. The code implementation is straightforward: ... const fetchAPI = async () => { try { await axios.get({ .... }) } catch (e) { console.error(e) } } R ...

How to send arrays through JSON?

I have some PHP code: $ids = array(1,2,3); $names = array("cat","elephant","cow"); $originalSettings = array ('ids'=>$ids,'names'=>$names); $jsonSettings = json_encode($originalSettings); echo $jsonSettings; Here ...

What is the best way to inquire (or conduct a Google search) on combining objects from various database models?

I'm faced with the challenge of displaying objects from two distinct mongoDB database models simultaneously on a single index page. Currently, these two sets of data are separated onto different index pages due to my lack of foresight. The issue I&ap ...

A guide on extracting JSON data from a script tag using Cheerio

I am in the process of extracting metadata from various websites. While utilizing Cheerio to retrieve elements like $('meta[property="article:published_time"]').attr('content') works smoothly for most sites, there are some whe ...

Counting the number of PHP inputs in a field

Hello, I am using a PHP script from Steve Dawson's website. To display the output on my HTML page, I am utilizing this AJAX script: <script> $.ajax({ type:'GET', url:'http://www.solariserat.se/count.php', data: ...

Speedily deliver a message to the designated destination

I have a specific route set up at /test: app.route('/test', (req,res)=>{ res.sendFile(__dirname + "\\myhtml.html") }) Now, I want to trigger an event in Node.js on the /test route, and have myhtml.html file listen for ...

Need help implementing the disableGutters property on MTableToolbar?

I am currently using react material-table and I would like to customize the default toolbar styles by passing the prop disableGutters={true}, similar to how it's done in material-ui toolbar. Below is the code snippet that I have tried: <MaterialTab ...

Show pagination control only when there are multiple pages in AngularJS using ui-bootstrap

Currently, I am working with ui-bootstrap pagination and facing an issue where the pagination controls are still visible even when all the results are displayed on a single page. A quick glance at the image below confirms this problem. It seems like a basi ...

Having trouble with React Page crashing when trying to access the component state

I'm attempting to create a side-bar menu that swaps out content in a <main> tag when menu buttons are clicked. However, I'm facing an issue where the page becomes unresponsive and eventually crashes due to React issues while trying to read ...

Acquire the value of ant-design Select dropdown upon hover

How can we detect the selected option in an ant-design dropdown when it is hovered? <Select defaultValue="lucy" style={{ width: 120 }} onChange={handleChange}> <Option value="jack">Jack</Option> <Option value=& ...

Why would triggering an input event have any effect if it doesn't appear to be utilized anywhere?

We have developed a custom Vuetify 3 component known as FilterPanel. Here is a simplified version: <template> <div> <v-container> <v-row> <v-col cols="3"> <v-select v-model="fiel ...

JavaScript button with an event listener to enable sorting functionality

I am looking to implement a button that will reset all the filters on my page. Any ideas? Currently, I have multiple radio buttons for filtering items based on price, size, and color. My goal is to create a reset button that will remove all filters and r ...

Creating dynamic images in JavaScript by assigning URL paths from string variables

Currently, I am utilizing JavaScript to parse through an XML file. One interesting aspect of the XML is that it contains URLs which link to images like this one: http://localhost/pic.jpg Throughout the parsing process, I am storing each URL as a string va ...

What could be causing this Angular controller to throw the error message "Error: Unknown provider: nProvider <- n"?

Check out the jsFiddle code here: <div ng-app=""> <div ng-controller="FirstCtrl"> <input type="text" ng-model="data.message" /> {{data.message + " world"}} </div> </div> function FirstCtrl($scope) { ...

Issue: Unable to locate element with the specified selector: #email

const puppeteer = require('puppeteer'); (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto('https://discord.com/register'); await page.screenshot({path: 'b.png ...

Ways to display output on a single line using javascript

It seems like such a simple task, but no matter how I try, I cannot get proper spacing between my words. /s does not seem to work for me. Here is an example of what I have attempted: document.write('You have been alive' + */s userMsDays /s* + &ap ...

Populate the div with the URL parameter only when another span element is empty after a specified time interval using setTimeout

When displaying a person's name on a page, there are two different methods to consider. It can be extracted from the URL or retrieved from an email form in the CMS used. However, these two approaches sometimes conflict with each other. Currently, I h ...

Activate the feature of smooth shading using Three.js

When rendering an object with textures using MTL and OBJ files in Three.js, I encountered an issue where my model was displayed with flat shading. How can I enable smooth shading? var scene = new THREE.Scene(); var mtlLoader = new THREE.MTLLoader(); mtl ...

AngularJS Large file size

After successfully building the 5 MIN QUICKSTART app, I decided to minify it with webpack following the recommendations in the angularJS docs. To my surprise, the size of the minified AngularJS file turned out to be approximately 700 KB, which is significa ...

Implementing JavaScript to Retrieve and Insert Full HTML Tags into a Textarea

I am currently trying to extract an HTML source code value and insert it into a specific textarea or div upon clicking a button. However, I am encountering issues where I am not receiving the entire HTML tags - it seems to begin with a Meta tag and is remo ...