0

I'm working on a piece of code to request information from an API. Throttles at 10 requests per second. My solution was to Promise.all(calculate(item1),calculate(item2)... ) and so forth for the 10 requests.

My approach was questionable to say the least, because when I have less than 10 items to check, my Promise.all is half done, and errors.

How can I populate Promise.All() to adapt to the length of the array?

I know this may sound idiotic and although my solution works, it's awful. I'm just a begginer and although I can handle some stuff, callbacks inside a Promise.all is way out of my league lol.

Thanks in advance!

async function superCalculadora(it){
    let res;
    if (it.length < 5) {
        if (it.length == 4) {
            res = await Promise.all([calculadora(it[0]),calculadora(it[1]),calculadora(it[2]),calculadora(it[3])]);
        }
        else
        {
            if (it.lenght == 3){
                res = await Promise.all([calculadora(it[0]),calculadora(it[1]),calculadora(it[2])]);
            }
            else
            if (it.length == 2){
                res = await Promise.all([calculadora(it[0]),calculadora(it[1])]);
            }
            else
            if (it.length == 1){
                res = await calculadora(it[0]);
            }
        }
    }
    else
    {
        res = await Promise.all([calculadora(it[0]),calculadora(it[1]),calculadora(it[2]),calculadora(it[3]),calculadora(it[4])]);
    }
JBaczuk
  • 13,886
  • 10
  • 58
  • 86
Max
  • 3
  • 6

1 Answers1

1

You could simply use Array.map and replace all of the above code with:

async function superCalculadora(it){
    const res = await Promise.all(it.map(item => calculadora(item)))
JBaczuk
  • 13,886
  • 10
  • 58
  • 86
  • THANK YOU! I never learned how to properly use some of those functions. That helps a lot!! You're awesome. You just cleaned up my code and saved me around 50% processing time. – Max Aug 29 '22 at 21:53
  • Awesome! I use most of the array functions regularly, definitely worth learning: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array. – JBaczuk Aug 29 '22 at 22:08