Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sending a sizeable array of Promises in Javascript

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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)))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading