Utilizing Promise.all() for handling multiple promises with multiple arguments

Currently, I am dynamically constructing a list of entries utilizing data retrieved from the server.

Each entry is associated with a parent. My objective is to extract the parent's name from the DOM by locating its ID. This process works effectively if the parent entry already exists on the page. However, it encounters errors if the parent entry is not present.

<div class="the_entry">
  <h4></h4>
  <select></select>
</div>
<script>
  const the_entry = document.querySelector('.the_entry');
  const parsed_data_from_server = [
    { entry_id: 0, entry_name: "zero", parent_id: 2},
    { entry_id: 1, entry_name: "one", parent_id: 2},
    { entry_id: 2, entry_name: "two", parent_id: 2},
  ];

  parsed_data_from_server.foreach((entry_from_the_server) => {
    // new div
    const new_entry = the_entry.cloneNode(true);
    the_entry.parentNode.insertBefore(new_entry, the_entry);
    new_entry.querySelector('h4').innerText = entry_from_the_server.entry_name;
    new_entry.querySelector('h4').id = entry_from_the_server.entry_id;
    // new option
    const new_option = document.createElement('option');
    new_entry.querySelector('select').appendChild(new_option);
    new_option.value = entry_from_the_server.parent_id;
    const name = document.querySelector(`[id="${entry_from_the_server.parent_id}"]`)
    new_option.innerText = name.innerText; // this will fail because no element with that id exists YET
  });
</script>

I am considering using promises to generate the option elements once the list processing is completed. Nonetheless, passing new_entry and entry_from_the_server is necessary for this task.

Here is my attempted solution...

let promises = [];
parsed_data_from_server.forEach((entry_from_the_server) => {
    // new div
    const new_entry = the_entry.cloneNode(true);
    the_entry.parentNode.insertBefore(new_entry, the_entry);
    new_entry.querySelector('h4').innerText = entry_from_the_server.entry_name;
    new_entry.querySelector('h4').id = entry_from_the_server.entry_id;
    // create a promise
    promises.push(new Promise((resolve, reject) => {
        resolve(new_entry, entry_from_the_server);
    }));
} );

Promise.all(promises).then((new_entries) => {
    new_entries.forEach((new_entry) => {
        // new option
        const new_option = document.createElement('option');
        new_entry.querySelector('select').appendChild(new_option);

        // where do I get entry_from_the_server from?!
        new_option.value = entry_from_the_server.parent_id;
        new_option.innerText = document.querySelector(`[id="${entry_from_the_server.parent_id}"]`).innerText;
    })
} );

Everything seems to be in order until the final stage... How can I acquire the second argument? Is there a way to achieve this?

Answer â„–1

When using the function resolve, it is important to note that only a single parameter should be passed. Any additional parameters will be ignored. For example, you can pass an object as follows:

promises.push(new Promise((resolve, reject) => {
     resolve({new_entry, entry_from_the_server});
}));

The resolved value will return an array where the first index contains the new_entry and the second index holds the entry_from_the_server:

Promise.all(promises).then((new_entries) => {
    //using destructuring
    new_entries.forEach(({new_entry, entry_from_the_server}) => {
        // new option
        const new_option = document.createElement('option');

        new_entry.querySelector('select').appendChild(new_option);

        new_option.value = entry_from_the_server.parent_id;
        new_option.innerText = document.querySelector(`[id="${entry_from_the_server.parent_id}"]`).innerText;
    })
} );

Answer â„–2

When using resolve(), remember that it only accepts one argument. However, JavaScript offers a simple solution - just bundle multiple arguments in an object and then resolve them:

promises.push(new Promise((resolve, reject) => {
        resolve( { entry: new_entry, serverEntry: entry_from_the_server } );

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 is the best way to remove an item from my online shopping cart using JavaScript?

I am currently developing an online store website. One issue I am facing is deleting items from the cart after a customer completes an order. Below is the array of cart items: const products = [ { id: '0', name: 'Nike Slim Shirt&ap ...

Filtering an array within an array based on user input

I am currently facing a challenge in filtering the child elements of an array. I am puzzled on how to specifically target children elements. So far, my filter is only functioning at the top level. Array: options: [ {name: 'Ð’Ñ‹Ñ…Ð ...

Transferring Live Information Between Two Controllers

How can I transfer the 'header' and 'content' from a controller's $scope element (specifically the 'header' and 'content') to another page that is redirected to upon clicking a button? The current setup involve ...

svg-to-json.js | The mysterious disappearing act of my file

After completing the installation process for svg-to-json.js as detailed in my previous post, I ran the command: node svg-to-json.js filename.txt The expectation was that a .json file would be generated, but I couldn't locate it. Is it supposed to ...

Error: The function .join is not recognized by the sockets.io library in a Node.js client-server environment

I'm currently working on developing a chat app using node and vue js, and I've encountered an issue with the socket.io library. Specifically, I keep receiving an error stating that ".join is not a function" when trying to use it in my server-side ...

Javascript: A guide on passing an object through multiple nested functions

Hey fellow developers, I'm facing a challenge in my code and seeking advice from the experts out there. I'm attempting to retrieve JSON data from a specific URL, as shown below, and utilize it in a React component outside of the getWeather() fun ...

What sets apart custom events from postMessage?

If you want to send a message to another document, such as an iframe, there are two functions you can use - postMessage and createEvent. Consider the following: var event = document.createEvent('CustomEvent'); event.initCustomEvent("message", tr ...

issue with manipulating URLs in Express routing

Looking for assistance with Express routing. I want users to only see localhost:3000/page2 when they go to /page2, instead of localhost:3000/page2.html I have three HTML pages - page1.html, page2.html, and page3.html. I've created a server using Expr ...

Having trouble with Lerna bootstrap? You might be running into the dreaded npm error code E401

Every time I run Lerna bootstrap on Jenkins, it fails with an error, but it works fine on my local machine. npm ERR! code E401 npm ERR! Unable to authenticate, need: BASIC realm="Sonatype Nexus Repository Manager" Package.json in the main folder ...

Fixing Firefox Bug: How to Eliminate Non-Numeric Characters from "Number" Input Fields

Completing this task seems straightforward. I need to eliminate any non-numeric characters from an input field specified as type "number" in Firefox when a key is pressed. The code snippet provided: $("#field").on("keyup", function() { regex = /[\& ...

Leverage ESlint for optimal code quality in your expressjs

Is there a way to use ESlint with Express while maintaining the no-unused-vars rule? After enabling ESlint, I am encountering the following issue: https://i.stack.imgur.com/7841z.png I am interested in disabling the no-unused-vars rule exclusively for e ...

Exploring the Intersection of Windows 8 Store Applications and jQuery: Leveraging MSApp.execUnsafeLocalFunction

Developing a Windows 8 JavaScript Store App (using Cordova) has led to some complications when using jQuery. It seems that in order to utilize certain functions, I have had to modify the jQuery library by adding: MSApp.execUnsafeLocalFunction While this ...

Show an SVG overlay when hovering over an image

Is there a way to create a hexagon shape around an image when it is hovered over using CSS only, even if the image itself has a circular border-radius of 50%? ...

When we typically scroll down the page, the next section should automatically bring us back to the top of the page

When we scroll down the page, the next section should automatically bring us back to the top of the page without having to use the mouse wheel. .bg1 { background-color: #C5876F; height: 1000px; } .bg2 { background-color: #7882BB; height: 1000px; } .bg3 ...

The npm module parsing has encountered an error... It appears that a suitable loader is required to process this file format

Recently, I made changes to an open-source code that was working perfectly until yesterday. I can't seem to figure out what went wrong as I didn't make any significant changes. Despite searching on Stack Overflow for a similar issue, my lack of k ...

React error: Updating state is only allowed on mounted or mounting components

I'm encountering this Error/Warning message in my console: The error message says: setState(...): Can only update a mounted or mounting component. Addressing the Component Mounting Process When it comes to mounting the component, here's the r ...

How to Insert PHP/MySql Data into JavaScript

As I delve deeper into PHP OOP, I feel like I'm making progress in transitioning my website. Currently, each user has their own page with a javascript grid tailored to their specific needs. For easier maintenance, I'm considering the idea of havi ...

Node.js NPM Google search results showing [ Object object ] instead of actual result

searchOnGoogle: function(searchQuery){ googleSearch.query({ q: searchQuery }, function(error, response) { console.log(response); botChat.send ...

What is the most effective way to identify mobile browsers using javascript/jquery?

As I develop a website, I am incorporating image preloading using JavaScript. However, I want to ensure that the preload_images() function is not called for users on slow bandwidth connections. In my experience, the main demographic with slow internet spe ...

Storing the DOM in a Variable

I have saved the response of an XMLHttpRequest() into a variable from a specific website, let's say yahoo.com. How can I retrieve the values of the DOM content using either getElementById or getElementsByName on this variable? For instance: var dump ...