How to run an async function after an async loop? A loop does not return a promise which means you cannot use await syntax to manage the execution order. What is a good way to make manage a loop like a promise.
This issue happens in my express routing. I tried to run the res.json after I retrieve data from reids DB with a loop, but res.json will run before the loop if I just put the code after it. Here I used a stupid way. I detect the last iteration of the loop and run my res.json function. I do not think this should be the right way of solving this issue.
app.get('/redisApi/v0.3/users', (req, res) => {
var users = [];
redis.scan(0, 'MATCH', 'user:info:*', 'COUNT', 10000).then(key_res => {
//where loop starts
for (let i = 0; i < key_res[1].length; i++) {
redis.hgetall(key_res[1][i]).then(user_res => {
const newOBJ = Object.assign(user_res);
users.push(newOBJ);
//detect last iteration of the loop
if (i === key_res[1].length - 1) {
res.status(200).json({
status: 'success',
data: {
users
}
});
}
});
}
});
});
Looking for a way to manage order of execution of loops.