When the Israelites direct their prayers to heaven, God's response serves a purpose that extends far beyond their immediate needs. By answering their calls for help, God causes His name to be magnified and recognized across the entire world [רש״י].
A significant part of this divine response involves delivering justice. In this situation, justice means taking decisive action against the idol-worshipping nations that have harmed the Israelites. The goal of this punishment is to make those nations clearly understand that God actively opposes the suffering and heavy burdens they force upon His people [מצודת דוד]. Therefore, the process is twofold: as God grants forgiveness to the Israelites for their own sins against Him, He simultaneously brings true justice to the nations that oppressed them.