[MODULES-195] Avoid infinite loop when iterating over modules.

Simply adding an exit condition from the loop if the nested iterator still contains some elements.