I have suffered from this for over 40 years; worse since I have been aggressively medicating my hypertension. Never fainted in all that time. If you can, bend over to lower you head when you feel it coming on. Also kneel down if you can to avoid injury in case you do faint. I know these things are embarrassing in public. Just make do.
As for prevention, I find that rehydrating after riding is extremely important. Also reloading electrolytes and carbs. Dehydration and low sodium are prime causes of this problem, so be sure to get your hydration, electrolyte levels back up quickly. The carbs also help.