One simple reason is that they are looking for food. This doesn't necessarily mean they are actually hungry. Apparently, goldfish will eat until they explode, so to speak, they simply do not know when to stop.
Occasionally, they mistake tiny air bubbles for food, and hey presto, they look like they are gasping for air. Unfortunately, this can lead to other problems by allowing air to enter the digestive tract.
To avoid this, it may help to soak the fish food a little before feeding it to the goldfish. The flakes will then sink quicker and get the fish used to eating lower down in the water.
Gasping for air might actually be another reason. If the water does not contain enough oxygen to sustain them, they will grab what they can from the top of the water to survive.
It is best to check out the water quality; high levels of nitrate in particular can affect goldfish. Regular changes of water and extra provision of oxygen, perhaps via a small pump, may help.
Another reason for gulping air could be that they are adjusting their swim bladders. Again, high nitrate levels may be affecting the fish. They then use the gulped up air to adjust their swim bladder in order to stop themselves from flipping over.
Another possible reason for adjusting swim bladders could be gas in their digestive tracts, which can be caused by grains in some foods.
This can be remedied by feeding them defrosted frozen peas with the shells removed. Basically acting like a laxative, they will help to clear their digestive tracts.
Once cleared, it is best to try feeding them with another type of food.