How can computers predict the outcome of an election soon after the polls but before all the votes have been counted?

They use what are called exit polls, interviewing people who have already voted. Assuming that they are a random and representative sample for the voting district or state, the percentages measured are applied to the total electorate.

Exit polling does not have to be done in all voting precincts, but those that are spolled should be representative of the state or congressional district as a whole.