Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make for loop asynchronous in JavaScript

I have a function that consists of a for a loop. Loop runs for a certain time and after that returns a value. my only aim is to return the value, once the loop runs entirely. I tried with Promise and Async-Await but none of them work for me.

Async Function

async function getTotalQuestion(tag, question) {
    var output = [];
    for (let i = 0; i < question; i++) {
        getOne(tag).then((data) => {
                output.push(data);
            })
            .catch((err) => {
                console.log(err);

            })
    }
    return output;
}

calling of the async function

getTotalQuestion('eco', 9).then((data) => {
        question = data; //here data is coming as undefined
    })
    .catch((err) => {
        console.log(err)
    })
like image 785
Pranay kumar Avatar asked Jul 30 '26 00:07

Pranay kumar


1 Answers

The problem in the above code is that it does not wait for getOne to push data into the output array. In order to get the correct output, you'll have to await the result of getOne inside the for loop.

async function getTotalQuestion(tag, question) {
    var output = [];
    for (let i = 0; i < question; i++) {
        try {
            var data = await getOne(tag);
            output.push(data);
        } catch (err) {
            console.log(err);
        }
    }
    return output;
}
like image 96
Kunal Kukreja Avatar answered Aug 01 '26 20:08

Kunal Kukreja



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!