1

I'm trying to make a function that makes an iterable of promises programmatically to call them by using promise.all like this:

   const fetchRandomItems = async (numberOfItems) => 
   const myPromises = [fetchRandomItem, fetchRandomItem, fetchRandomItem] // The length of this array should be equal to numberOfItems
   promise.all(myPromises)
}

I dont know how to make myPromises's length equal to numberOfItems

Please and Thanks!

sankiago
  • 79
  • 9
  • Use a `for` loop? – Bergi Jul 09 '21 at 16:49
  • I don't really understand your problem, so the simplest thing i can suggest is `let mypromises = []; for (let i= 0; i < numberofitems; i++) myPromises.push(fetchRandomItem); Promise.all(myPromises)` where `fetchRandomItem` is a promise. If that isn't what you are asking, elaborate your question ... – derpirscher Jul 09 '21 at 16:50
  • https://stackoverflow.com/q/1295584/1048572, https://stackoverflow.com/q/34966459/1048572, etc – Bergi Jul 09 '21 at 16:51
  • Thaanks, I didnt realize that was a simple thing, thanks anyway ;) – sankiago Jul 09 '21 at 16:52

1 Answers1

2

You build an array as if promises were any other object.

const fetchRandomItems = numberOfItems => {
    const myPromises = [];
    for (let i = 0; i < numberOfItems; i++) {
        myPromises.push(fetchRandomItem());
    }
    return Promise.all(myPromises);
}

or

const fetchRandomItems = numberOfItems => 
    Promise.all([...Array(numberOfItems)].map(() => fetchRandomItem()))
rom
  • 101
  • 1
  • 8
  • thanks man, you really helped me a lot :D – sankiago Jul 09 '21 at 16:54
  • A question, in the 1st line of the for loop, when `myPromises.push(fetchRandomItem())` is runned, the `fetchRandomItem()` is made? – sankiago Jul 09 '21 at 16:56
  • 1
    @sankiago I'm not sure I understand your question, but this code assumes that fetchRandomItem() is an async function. Async functions return promises. – rom Jul 09 '21 at 16:57