I have a Javascript function that takes in an int argument and returns a promise. I also have an array of ints(variable length) and I would like to call my function multiple times passing in each int to it and return multiple promises in one function. How do I accomplish this? The closest I could find on SO was JS return multiple promises in one function
function myFunction(input)
{
return Promise.resolve(input);
}
/*
function invokedFunction(input)
{
return function myFunction() {return Promise.resolve(input);}
}
function waitForAll()
{
var resultArray = [];
resultArray = await callMyFunction();
}
*/
function callMyFunction(inputArray)
{
Promise.all[myFunction(pass in each item from inputArray)..... ];
/*
const promisesArray = [];
if(Array.isArray(inputArray)){
inputArray.forEach(function(item, index){
promisesArray[index] = invokedFunction(item);
});
}
return Promise.all(promisesArray);
*/
}
var inputArray = [1, 2, 3, 4, 5];
callMyFunction(inputArray);
var inputArray = [1, 2, 3, 4, 5];
function getPromiseArray() {
// Can use a for...of instead of .map if preferred
const promises = inputArray.map((item) => callMyFunction(item));
return promises;
}
Then if you want to await all promises
let results = await Promise.all(getPromiseArray())
Promise.all returns an array of the fulfillment values
A example function to just loop through the results
async function processPromises() {
try {
// Wait for all promises to resolve
const results = await Promise.all(getPromiseArray());
// Log each result
for (let result of results) {
console.log(result);
}
} catch (error) {
console.error("An error occurred while processing promises:", error);
}
}
Note: