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.