WASHINGTON — Riding in a motorcade in Lima, Peru, shortly after the 2016 election, President Barack Obama was struggling to understand Donald J. Trump’s victory.

“What if we were wrong?” he asked aides riding with him in the armored presidential limousine.

He had read a column asserting that liberals had forgotten how important identity was to people and had promoted an empty cosmopolitan globalism that made many feel left behind. “Maybe we pushed too far,” Mr. Obama said. “Maybe people just want to fall back into their tribe.”

His aides reassured him that he still would have won had he been able to run for another term and that the next generation had more in common with him than with Mr. Trump. Mr. Obama, the first black man elected president, did not seem convinced. “Sometimes I wonder whether I was 10 or 20 years too early,” he said.

In the weeks after Mr. Trump’s election, Mr. Obama went through multiple emotional stages, according to a new book by his longtime adviser Benjamin J. Rhodes. At times, the departing president took the long view, at other points, he flashed anger. He called Mr. Trump a “cartoon” figure who cared more about his crowd sizes than any particular policy. And he expressed rare self-doubt, wondering whether he had misjudged his own influence on American history.