0

I try to do multiple requests in for each loop and push data response to an array but I get always the first item only

//Get all roles
router.get('/', async (req, res) =>{

    try {

        knex.from( roles_table )
        .then(roles => {
            let rolePermissions =[];
            roles.forEach(role => {
                knex.select(permissions_table + '.*').from(permissions_table)
                    .innerJoin(permissions_roles_table, permissions_table + '.id', permissions_roles_table +'.id_permission')
                    .where(permissions_roles_table + '.id_role', '=', role.id)
                .then(rows => {
                    role.permissions = rows;
                    rolePermissions.push(role)
                });
                
            });
            
            res.status(200).json(rolePermissions);
            

           
        });
       
    } catch (err) {
        res.status(500).json({message: err});
    }
});
Tigran Abrahamyan
  • 756
  • 1
  • 4
  • 7
Boutamente abdessamad
  • 523
  • 2
  • 10
  • 30

1 Answers1

1

You must learn about Promise and asynchrone if you want to do modern JS.

Something like that could be what you are looking for

//This const will store an array of Promise
const allRows = knex.from( roles_table )
.then(roles => {
    return roles.map(role => {
        return knex.select(permissions_table + '.*').[...]
    });
});

//This method will wait for each promises to succeed or first one to failed
return Promise.all(allRows)
.then( allRows => {
    //allRows is now an array containing all the results
    res.status(200).json(rolePermissions);
})
.catch (err) {
    res.status(500).json({message: err});
});

By the way, you don't need try/catch a Promise, there is the .catch method

farvilain
  • 2,552
  • 2
  • 13
  • 24