Guide on making an array of unresolved promise functions

I am facing an issue with constructing the promisesArray.

While this approach works perfectly, I need to dynamically build this array.

var promisesArray=[get(url1),get(url2),get(url3)];  // url1,url2,url3 are valid urls here

var promises = Promise.all(promisesArray);

promises.then(function(results) {
 console.log('this came back: ',results);
}).catch(function(error) {
  console.log(error);
});;

function get(url) {
  // Return a new promise.
  return new Promise(function(resolve, reject) {
    // Perform XMLHttpRequest actions

  });
}

The challenge lies in creating the promisesArray where each element is a promise. Every attempt I make only adds the result of calling get() rather than the promise itself, resulting in an array of pending promises:

Array [ Promise { "pending" }, Promise { "pending" }, Promise { "pending" }]

What I actually want is:

promisesArray=[get(url1),get(url2),get(url3)];

For instance, I attempted the following:

let template=['a','b','c','d'];

var promiseArray=[];
template.forEach(function(pos){
    let url=lookupUrl[pos]](); 
        promiseArray.push(get(url));
})

However, it simply returns the result of the get call.

Even when trying to use bind, I still end up with an array of executing promises:

 var promiseArray = template.map(function(pos){
   var url = lookupUrl[pos]]();
   var out= get.bind(null,url);
   return out()
 })

I am unsure how to create an array of functions that have not been called yet.

[EDIT_UPDATE] As pointed out by @JaromandaX and @Roamer-1888, I already had what I needed and either of the above methods should work for creating the array of promises. My focus on having an array of 'uncalled functions' was unnecessary.

I find the approach suggested by @HMR intriguing and intend to give it a shot.

Answer №1

Maybe what you're searching for is a map function:

Promise.all(
  routes.map(retrieve)
)

In case you have an array of models, map them to URL first and then to promises:

const models=['x','y','z','w'];

Promise.all(
  models.map(//map position to URL
    position=>fetchURL[position]()
  ).map(//map URL to promise
    retrieve
  )
);

If there's a need to control the flow in some way, consider checking out this solution.

Answer №2

Have you considered creating an array of functions that will return promises and then delaying their execution until they are inside Promise.all?

var promiseFunctions = [() => get(url1), () => get(url2), () => get(url3)];

Promise.all(promiseFunctions.map((func) => func()))

By following this approach, all the get requests will be initiated simultaneously and the promise from all won't resolve until all requests are completed.

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

Obtain the height and width of the original images from the href and assign them to your attributes using jQuery

Hey there pals, I'm currently on a mission to fetch the dimensions (height and width) of an image from a hyperlink and then insert those values into its attribute. This task has got me going bonkers! Here's my snippet: <figure> <a ...

Is it feasible to package shared modules into individual files using Browserify?

In my web app, I am using Browserify, Babel, and Gulp to bundle my scripts into a single file. However, when I checked the file size, it was over 3MB which seems excessive to me. Although I'm not entirely sure how Babel and Browserify modify my sourc ...

Synchronizing information between different controllers using a service

After reading the discussion on this stackoverflow post, it seems like using services is the recommended way to transfer data between controllers. However, in my own testing on JSFiddle here, I encountered difficulties in detecting changes to my service w ...

A different approach to splitting strings

After receiving a GET request, I am presented with a string that has the following format: <?xml version="1.0" encoding="utf-8"?> <string xmlns="http://myUrl.com">you said:This is a test --&gt;SHA1:7d9d2886509cfd1dfd3c693fff43b82561ec00a18 ...

Incorporating exotic elements into d3.js, currently visible

I am attempting to insert checkboxes and text within a node. Refer to the image below for my desired outcome. https://i.sstatic.net/YhrvZ.png While I can see the checkbox in the elements view, it is not visible on the page itself. https://i.sstatic.net/ ...

Solution for adjusting line width on Windows in Three.js

I'm currently working on creating a dynamic 3D coordinate system using the Three.js library. My goal is to add some thickness to the axes, which I've been able to achieve by adjusting the LineBasicMaterial's linewidth parameter. The code sn ...

Embed an event into an HTML div that is not editable

How can I bind the paste event on a div to grab an image from the clipboard and assign it to an Angular scope variable? This solution works in Chrome, but not in IE 11 without adding the contenteditable=true attribute. However, using content editable break ...

Discovering information from a URL through JSON

Can someone help me with loading and displaying this JSON data? I attempted the following code, but unfortunately, it did not work as expected. <script> $(document).ready(function(){ $.getJSON("http://eolis-sante.com/eolis/connexion.php? ...

Intersecting a line with a sphere in ThreeJS

I am working with a scene that includes a red line and a sphere. As the camera rotates, zooms, or moves, I need to check if the line intersects with the sphere from the current camera position (refer to the images below). To visualize this scenario, pleas ...

What is causing the breakdown in communication between my server and client?

While utilizing React and an Express server for the backend, I am facing an issue where my API call to server.js is not going through. The React client is running on port 3001 and the server on port 3002. The fetch code in CreateAccount.js is as follows: ...

Error encountered in Browserify bundle.js: exec function is not executable

After setting up Node.js, npm, samba-client, and browserify on my system, I encountered a frustrating issue in my bundle.js file. An Uncaught TypeError related to the 'exec' function has been causing trouble, and despite my efforts, I have been u ...

Using a shortcode as a variable in WordPress can enhance the functionality and customization

I have a button shortcode set up on my website that I want to use consistently across all of my posts. My goal is to be able to update the button's details centrally so that any changes made will be reflected in every instance without having to go thr ...

How does Node.js contribute to the MEAN stack ecosystem alongside JavaScript and Express, in contrast to Django and Python?

Having experience in developing web applications with Python, Django, and PostgreSQL, I have now shifted my focus to JavaScript and the benefits of the MEAN stack. MongoDB serves as the database for MEAN, similar to how PostgreSQL is used with Python. Expr ...

Using memoryviews in Cython to store an array

Expanding on this solution from a previous inquiry, I am interested in creating arrays of memoryviews. Issue 1 Create a 2D array of memoryviews with fixed lengths, for example: mv1 = memoryview(b'1234') mv2 = memoryview(b'abcd') cdef ...

Change a single line of javascript into code that is easier to understand

Having some trouble comprehending this concise line of Javascript code. The following line is functioning: this._iconNeedsUpdate = !0,this._expandBounds(t), t instanceof L.MarkerCluster ? (e || (this._childClusters.push(t), t.__parent = this), this._chil ...

What is the best way to retrieve and obtain all relationship data as an array of objects using MySQL queries?

Assume there are three tables Primary table +----+------+---------------------+ | id | name | create_at | +----+------+---------------------+ | 1 | jack | 2023-04-26 22:01:37 | | 2 | tom | 2023-04-26 22:01:37 | +----+------+---------------- ...

The Vue.js edit component is first organized by lodash before being saved

In my Vue.js component, I have a feature that allows users to edit items inline. I'm using lodash to sort the items by name, but the issue is that every time a key is pressed, the array gets sorted immediately and causes a strange position change. The ...

Electron's Express.js server waits for MongoDB to be ready before executing queries

As I work on a demo application, Express serves some React code that interacts with a MongoDB database hosted on mLab. The data is retrieved using SuperAgent calls in my main React code loaded via index.html. While everything works fine when starting the ...

Display a specific template in the detail grid of the Kendo Grid depending on certain conditions

I've been using the Kendo Grid and it's been working well for me. I have a requirement to check each row in my grid to see if it contains a specific value, and based on that, bind data using different templates. Is this feasible? Below is the cod ...

Received an error while working on web development in Bootstrap with npm

I recently watched a freeCodeCamp video tutorial on web development which can be found here. Despite following the tutorial step by step, I encountered the following error message while running the webpack script: PS C:\Admin-Dashboard> npx webpac ...