Devas and Asuras performed Samudra Manthan (churning of ocean) to get Amrita, the nectar of immortality. But when Amrita was received from the ocean both Devas and Asuras fought over it. When there was no end to the fight, Vishnu appeared in the enchanting female form of Mohini.
Both Devas and Asuras were smitten by the beauty of Mohini and agreed to her idea of distributing the Amrita. Vishnu did not want Asuras to consume Amrita as this will make them immortal and then they will create havoc in the universe.
So Mohini first poured Amrita into the mouth of Devas. One Asura got suspicious about the whole event and went and sat among the Devas. When Mohini poured Amrita into the mouth of the Asura, Surya (Sun God) and Chandra (Moon God) who were sitting nearby recognized the intruder and alerted Mohini.
Mohini then took the form of Vishnu and cut the neck of Asura with Sudarshana Chakra. The head of the demon became Rahu and the body became Ketu.
To avenge, Rahu promised that he will eclipse sun and moon periodically and this results in eclipse.
Ketu became a directionless comet in the sky.