Ali Muqaddas
Ali Muqaddas

Reputation: 39

How to give Promise to For Loop in NodeJS

How to stop nodeJS to execute statements written outside for loop till for loop is completed?

for(i=0;i<=countFromRequest;i++)
{
    REQUEST TO MODEL => then getting result here (its an object)
    licensesArray.push(obj.key);
}
res.status(200).send({info:"Done Releasing Bulk Licenses!!!",licensesArray:licensesArray})

The problem is that the statement after For Loop is being executed before For loop, so the licensesArray is empty when i receive the API Data.

Any clue how to do that?

Will be thankful to you.

Upvotes: 1

Views: 47

Answers (1)

Christian Santos
Christian Santos

Reputation: 5456

Using async/await:

const licensesArray = [];

for(let i = 0; i <= countFromRequest; i++) {
    const obj = await requestModel(); // wait for model and get resolved value
    licensesArray.push(obj.key);
}

res.status(200).send({licensesArray});

Using Promise.all:

const pArr = [];
const licensesArray = [];

for(let i = 0; i <= countFromRequest; i++) {
    pArr.push(requestModel().then(obj => {
        licensesArray.push(obj.key);
    }));
}

Promise.all(pArr).then(() => { // wait for all promises to resolve
    res.status(200).send({licensesArray});
});

I would go with async/await if your environment supports it, as it makes things easier to read and lets you program with a synchronous mindset (under the hood it's still asynchronous). If your environment does not support it, you can go with the Promise.all approach.

Further reading:

Upvotes: 1

Related Questions