How can the order of elements appended to a documentFragment be controlled when they are returned asynchronously?

Curious question here...

I am constructing my in-memory DOM and relying heavily on promises. Let's say I have this snippet inside a loop:

target = document.createDocumentFragment();
promises = [], pass, skip, store;

for (i = 0; i < foo; i += 1) {
    element = foo[i];

    // set promise
    promises[i] = app.setContent(element, {}, update)
        .then(function(response) {
            // HELP!
            if (pass) {
              target.appendChild(store)
              store = undefined;
              skip = undefined;
              pass = undefined;
            }
            if (response.tagName !== undefined) {
              pass = true;
            }
            if (skip === undefined && response.tagName === undefined) {
              store = response;
              skip = true;
            } else {
              target.appendChild(response);
            }
          });

  RSVP.all(promises).then(continue...

This particular loop operates 3x returning two div tags and a documentFragment. Previously without promises, the structure looked like:

 <div toolbar>
 <fragment = form>
 <div toolbar>

The issue arises when converting to async, where the order of appending items is no longer predictable. This leads to convoluted workarounds like the one shown above with setting flags and conditions for sequential appendages - not exactly efficient or elegant.

Question:
Is there a more streamlined way to dictate the order of async returned items in a universal manner? If not, how can items be rearranged efficiently? Utilizing methods like querySelector/qsAll would provide some flexibility, but are there any other suggestions?

(And let's avoid the suggestion of placing content in the actual DOM just to reorder it :-) )

Thank you!

Answer №1

Allow me to clarify using plain language...

When sending an asynchronous request, be sure to create a designated container where the requested data will be placed once it is received. This container is usually a <div> or a <span>.

Maintain a connection to the container (often within a closure) so that the async response handler can accurately match containers with their respective data.

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

All outcomes being displayed from Youtube's json feed

Currently, I am retrieving a youtube playlist by using the following link: I'm curious if there is a method to display all 250 videos from my feed instead of just the 25 that are currently being shown. Any assistance on this matter would be highly a ...

Can you explain the meaning of arguments[0] and arguments[1] in relation to the executeScript method within the JavascriptExecutor interface in Selenium WebDriver?

When utilizing the executeScript() method from the JavascriptExecutor interface in Selenium WebDriver, what do arguments[0] and arguments[1] signify? Additionally, what is the function of arguments[0] in the following code snippet. javaScriptExecutor.ex ...

Is it possible to run an existing NextJS app with API routes on a mobile platform using either Capacitor or Expo?

I have an established NextJS application that heavily relies on Next's API routes. My goal is to transition the current codebase to function in a mobile environment. I've experimented with Capacitor and attempted to export it as a static site, bu ...

Using jQuery to find and replace specific text starting from the nth instance

Input information = '/hello/world/test' I am trying to achieve the output 'hello-world-test' using jquery. I have experimented with methods like splice, replace, and a custom condition (see code snippet below). However, I have not bee ...

Uh oh! React encountered a cross-origin error and is unable to access the real error object during development

I've encountered an issue while attempting to extract and display data from the student_learn field in firestore. Despite my efforts to map it to jsx components, I keep receiving a cors-origin error. Below is a screenshot of the collection I'm tr ...

Encountering an HTTP parsing failure while sending XML through Angular 5's HttpClient

Struggling to access a local webservice through XML: Take a look at the code below: const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'text/xml', 'Accept': 'text/xml', 'Response- ...

How can I apply a jquery method to a variable when JavaScript already has a method with the same name?

Is it possible to call the .which function on a character without needing to differentiate between browser types by using the jQuery .which method, which supposedly normalizes for browser discrepancies? I know that the inherent javascript method is also ...

Invalid character entered into HTML5 number input field

How can I validate a number field on my own when element.value returns nothing in Chrome if the content is alphabetical? Setting 'novalidate' on the form does not prevent this issue. As a result, I am unable to distinguish between an empty entry ...

What is the best way to utilize useEffect solely when the length of an array has

Is there a way to trigger a state update only when the length of the prop "columns" changes? useEffect(() => { if (columns.length !== prevColumns.length) { // update state } }, [columns]); Any suggestions on how to achieve this? ...

Trouble with jQuery UI add/remove class duration feature

I have implemented Jquery UI with the addClass/removeClass function successfully. However, I am facing an issue where the class changes without the specified duration. Below is the relevant code snippet: <script src="https://ajax.googleapis.com/ajax/li ...

Creating a persistent toolbar in Vuetify: Tips and tricks

Within my Vuetify app, I've implemented a toolbar: <v-toolbar dark color="primary"> <v-toolbar-side-icon @click.stop="drawer.drawer = !drawer.drawer"></v-toolbar-side-icon> <v-toolbar-title>{{drawer.title}}</v-toolb ...

Is there a way to make a text area move along with the mouse cursor?

I have been working on my first website and everything is running smoothly so far. However, I have a new idea that I am struggling to implement. Some of the pages on my site feature a video player with buttons to select different videos. When a viewer hove ...

I am facing an issue where the HTML button is not properly interacting with the JavaScript function

function idk() { let cypher = {A:"G",B:"L",C:"Z",D:"E",E:"Y",F:"R",G:"D",H:"N",I:"K",J:"W",K:"J",L:"B",M:"Q",N:"F",O:"S",P:"C",Q:"V",R:"X",S:"I",T:"O",U:"M",V:"T",W:"A",X:"U",Y:"H",Z:"P"}; var answer = prompt('What cypher are you going to use 1 - 26& ...

When trying to convert a function component to a class component, using `npm init react-app` may result in the error `ReferenceError: React is not defined no-undef`

After running npm init react-app appname, I noticed that the file App.js was created, containing a function component: function App() { return ( <SomeJSX /> ); } I decided to change this function component into a class component like this: c ...

The array used within the useEffect hook and the getCoordinates function appears to be distinct when printed with console

Utilizing GoogleMap API for Custom Location Display I have an imported array of JSON objects named data which includes an address property. The Google Maps API is used to retrieve coordinates from the addresses in order to generate custom markers displaye ...

Increasing the maximum width of an image in CSS is necessary to see the max-height take effect

Within my HTML structure: <Col md="6"> <div className="hero-section"> <div className={`flipper ${isFlipping ? "isFlipping" : ""}`}> <div className="front"> <div className="hero-section-content"> ...

What signals to Angular that $httpBackend is substituting $http during the testing of AngularJS?

My factory, called myFactory, has a dependency on $http. When writing tests for this, I needed to mock this dependency. After some research, I discovered that I could accomplish this using $httpBackend. Implementing the code below successfully achieved t ...

Tips for creating an illustration in Vue.js

As I attempt to create an image using canvas, my browser throws this error at me: Uncaught TypeError: Cannot read property 'drawImage' of undefined at Image.img.onload (test.js:23) To troubleshoot, I added some console.log() messages and here ...

What is the specific jQuery event triggered when utilizing the append function on a textarea element?

I am currently setting up a system to detect any modifications in a textarea: <textarea id="log-box__data"></textarea> Modifications are made to the textarea exclusively using jQuery's append method: $(document).on('click', &a ...

Creating a unique Nest.js custom decorator to extract parameters directly from the request object

I am working with a custom decorator called Param, where I have a console.log that runs once. How can I modify it to return a fresh value of id on each request similar to what is done in nestjs? @Get('/:id') async findUser ( @Param() id: stri ...