简体   繁体   中英

How to get response after Loop of requests finished

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM