Home > Software design >  How to execute a variable-sized array of promises in Javascript
How to execute a variable-sized array of promises in Javascript

Time:08-30

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])]);
    }

CodePudding user response:

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)))
  • Related