0

i have this function for return array of string .

 async GetAllPermissonsByRoles(id) {
    let model: string[] = [];
    try {
        id.forEach(async (role) => {
            let permission = await RolePermissionModel.find({ roleId: role._id })
                .populate({
                    path: 'permissionId',
                    model: 'Permission'
                });
            permission.forEach((elment) => {
                model.push(elment.permissionId);
            });
        })
    } catch (error) { }

    return model;
}

but i have a problem with this code , in this function not wait for complete forLoop and then return model , loop is not complete yet but returns the value .

whats the problem ? how can i sovle this problem ?

Update :

i write this code but still have that problem :

  async GetAllPermissonsByRoles(ids) {
    let model: string[] = [];
    try {

        await Promise.all(ids.map(async (role) => {
            let permission = await RolePermissionModel.find({ roleId: role._id })
                .populate({
                    path: 'permissionId',
                    model: 'Permission'
                });
            await Promise.all(permission.map(async (permission) => {
                permission.forEach((elment) => {
                    model.push(elment.permissionId);
                });
            }))
        }))
    } catch (error) { }

    return model;
}
kianoush dortaj
  • 411
  • 7
  • 24

1 Answers1

2

You can't use forEach with async/await. Please read this as explanation async await with forEach

cvekaso
  • 833
  • 1
  • 11
  • 28
  • @kianoushdortaj you don't need second ```await Promise.all``` you just need to go through the permission, because you only need to await for getting from the database -> RolePermissionModel and then you do iteration through the result – cvekaso Oct 10 '20 at 11:58