It was on his second day as Mayor of London that Sadiq Khan made Donald Trump look more absurd than any US politician or reporter has managed. Challenged over whether his proposed ban on Muslims entering the United States would apply to Khan, the blustering tycoon replied: “There will always be exceptions . . . Frankly, if he does a great job, that would be a terrific thing.”

In his response, the new mayor showed no mercy. “Donald Trump’s ignorant view of Islam could make both our countries less safe,” he said. “It risks alienating mainstream Muslims around the world and plays into the hands of the extremists. This isn’t just about me – it’s about my friends, my family and everyone who comes from a background similar to mine, anywhere in the world. Donald Trump and those around him think that Western liberal values are incompatible with mainstream Islam. London has proved him wrong.”

The election of the first Muslim mayor of a major Western city was always destined to be a momentous event. But its coincidence with the rise of demagogues such as Trump and France’s Marine Le Pen has given it even greater potency. By electing Khan, one of the world’s pre-eminent cities has repudiated the “clash of civilisations” thesis. His victory is a retort both to conservative nationalists who insist that Muslims cannot integrate and to Islamist extremists who insist that they should not.

Its significance was globally recognised. “London elects Muslim mayor in tense race”, read the front page of the New York Times. “Son of a Pakistani bus driver, champion of workers’ rights and human rights, and now Mayor of London. Congrats,” tweeted Hillary Clinton. “The mayoral election shows that London is more liberal, clever and tolerant than the conservative mudslingers would like to think,” declared the German news magazine Der Spiegel. “Khan’s story should help set the record straight on immigration, integration and European Muslims,” concluded Pakistan’s Dawn newspaper.

For progressives, the London mayor is the anti-Trump: a liberal, pluralist counterweight to conservative xenophobia. Adherents of the latter have also been animated by Khan’s victory: the right-wing US website the Drudge Report bemoaned the success of the “first Muslim Mayor of Londonistan”.

Khan’s team had long anticipated the international resonance that his victory would have. A source told me that it was “highly likely” that his first foreign trip would be to the United States. One possibility is an appearance at the Democratic National Convention in July.

The new mayor has long enjoyed close links with his left-leaning New York counterpart, Bill de Blasio, who attended the 2014 Labour conference. Since his election in late 2013, de Blasio has ended police surveillance of Muslim residents, expanded universal childcare and increased the supply of affordable housing. Khan’s promised Skills for Londoners task force is modelled on de Blasio’s Jobs for New Yorkers.

On 9 May, responding to Khan’s election, the White House hailed a “historic development for a historic city”. The following day, Trump performed his volte-face. “He [Khan] will be a key figure in showing that liberal western democracies can unite against Trump and Trump-style policies that just seek to divide communities,” a source told me. “That’s what Sadiq’s all about. He’s all about unifying and not dividing.”

***

Khan did not merely win the London mayoral election. With 1,310,143 votes, he achieved the largest personal mandate of any politician in UK history. His Conservative opponent, Zac Goldsmith, was beaten in the final round by 57-43, the second-widest margin since the mayoralty was established in 2000.

Khan’s strategists cited four insights as central to his success. The first was that personality matters more than policy. Having seen Ed Miliband defined by his opponents (“weak”, “weird”, “treacherous”), Khan’s team “set out hard and fast to paint a picture of who he was”. His election leaflets rooted his policies in his personal story: “the bus driver’s son who’ll make commuting more affordable”, “the council estate boy who’ll fix the Tory housing crisis” and “the British Muslim who’ll take on the extremists”. By the end of the campaign, journalists groaned at the mention of his bus driver father – a sure sign of success.

The second insight was that policy should be announced early and then endlessly re-announced. All of Khan’s signature pledges – the fares freeze, “first dibs” on new homes, the “London Living Rent” – were made by January.

The third insight was that winning campaigns do not adopt a “35 per cent strategy” – shorthand for Miliband’s narrow focus on Labour’s core vote and former Liberal Democrats. In contrast to Ken Livingstone, who sought victory through a rainbow coalition of left-wingers, Khan spent more time in Tory-leaning parts of outer London than in the city’s inner half. He engaged positively with all media titles, including the Sun, the Daily Mail and City AM. The fourth insight was to anticipate opponents’ attacks. Khan was talking about his Muslim background and emphasising the duty of British Muslims to help combat extremism from the beginning of his campaign.

Though history may record Khan’s victory as inevitable – London is a Labour city, as commentators often observe – few initially believed it was so. Throughout the contest, MPs worried that low turnout or the “Bradley effect” could deny him success. The latter refers to the 1982 California gubernatorial election in which an African-American Democratic candidate called Tom Bradley lost even though he was leading his Republican rival in public surveys. White voters didn’t want to vote for a black man but didn’t want to admit that to pollsters. The fear of this phenomenon was heightened by Goldsmith’s campaign, which smeared Khan as a fellow-traveller of Islamist extremists, a suggestion that David Cameron and Boris Johnson echoed.

Many in Labour believe that this approach harmed the Conservatives. They speak of how hitherto indifferent voters were moved to participate by their repugnance at the Tories’ tactics. A series of sectarian leaflets targeted at British Indians, falsely alleging that Labour supported a “wealth tax on family jewellery”, backfired particularly badly. Rather than reaching a new low (after the end of the Ken v Boris show), turnout rose to a record high of 45.6 per cent, up from 38.1 per cent in 2012.

Khan’s victory did not just counter the prejudice of the right. It also undercut the pessimism of the left, which sometimes overestimates or exaggerates the electorate’s conservatism. “The Bradley effect – that’s a US election from 34 years ago. That attitude has been a barrier to the selection of minority candidates,” Sunder Katwala, the director of British Future, told me. “People who are perfectly progressive say, ‘Well, of course we’d do it – but will the voters buy it?’ It’s actually important to make it clear you can get over that.”

Goldsmith’s campaign drew on the “dog-whistle” tactics that the Conservatives deployed in the 2005 general election – the use of coded language to influence subgroups (Khan was tellingly labelled a “radical”). Yet, as the former Tory mayoral candidate Steven Norris observed: “Dog-whistle politics is fine but not in a city where everybody else can hear it. This is the most cosmopolitan, the most relaxed, the most genuinely integrated major city in the world.”

Khan’s election was followed by that of the Labour candidate Marvin Rees in Bristol – the first directly elected city mayor in Europe of African or Caribbean heritage. Their victories reflected and reinforced the diverse character of the UK. In London, black and minority ethnic voters account for 44 per cent of the total; in Bristol, they represent 22 per cent. “Diversity is the new normal in UK politics,” Katwala said.

When the Britain First candidate Paul Golding sullenly turned his back as Khan delivered his acceptance speech, it felt like the last gasp of a dying order. In the US, where black and Hispanic voters account for more than 30 per cent of the total, Trump may similarly suffer death by demography.

At his swearing-in ceremony on 7 May at Southwark Cathedral (a venue specifically chosen by his team), Khan was introduced by Doreen Lawrence, the mother of the murdered black teenager Stephen. She told the crowd: “I never imagined in my lifetime I could have a mayor of London from an ethnic-minority background.”

Before leaders of several faiths and with many audience members in tears, Khan pledged to be “a mayor for all Londoners”. His words were a repudiation of both Goldsmith’s divide-and-rule tactics and the communalism of the former mayor Ken Livingstone. In 2012, Livingstone was reported to have told a group of Jewish Labour activists that because their community was “rich”, it “simply wouldn’t vote” for him.

From the outset of his mayoral campaign, Khan sought to repair the relations strained by his Labour predecessor. He attended a Passover celebration (wearing a kippa), met shoppers at a kosher market and condemned his party’s “anti-Jewish” image. His first official engagement as mayor was a Holocaust memorial event in Barnet, where he appeared alongside Chief Rabbi Ephraim Mirvis. “That is a great message to send to British Muslims,” Mohammed Amin, the chairman of the Conservative Muslim Forum, told me. “Our relationship with the Jewish community should be one of friendship, support and solidarity, rather than allowing ourselves to be divided because of the Israeli-Palestinian conflict.” In the hours before Khan’s victory, a sharp contrast was provided by Livingstone, who resurfaced on TV and continued to defend his claim that Hitler supported Zionism. Once again, it felt like the last gasp of an ancien régime.

Khan’s strategists say that one of his long-term priorities as mayor will be to improve social cohesion. Though lauded for its melting pot status, London is proportionally less ethnically integrated than the rest of the the UK. In his speech to the Parliamentary Press Gallery on 19 November last year, he lamented: “Too many British Muslims grow up without really knowing anyone from a different background.” He warned that the political establishment had for too long “tolerated segregation” at the expense of “creating a common life”. He will use his mayoralty to promote the compulsory learning of English, which he views as “the only way to communicate with neighbours, apply for a job, speak to instructors at your children’s school and to fit in the British community”.

As he seeks a legacy, David Cameron is similarly focused on combating extremism. The election of a Muslim as Mayor of London is a powerful asset in doing so. But Cameron’s campaign attacks on Khan meant he could not welcome his victory in the manner liberal Tories had hoped. The mayor, however, was unruffled. “I’ll work with anybody when it’s in London’s interests,” he told me after the ceremony in Southwark. “I’m looking forward to working with the Prime Minister when it comes to us remaining in the EU, when it comes to infrastructure investment . . . What’s important is to put aside the past, put aside party political differences and put London first.”

When Cameron eventually congratulated Khan by phone on 8 May, he made it clear that he “really needed his help” over the EU. Yet there was no remorse expressed for the Tory tactics deployed against him. The Defence Secretary, Michael Fallon, has refused to say whether he believes that London is safe under Khan. At the Parliamentary Labour Party (PLP) meeting on 9 May, Khan declared: “We can’t let the Tories off the hook just because they lost. The Tory party owes London an apology.” There is speculation among Tories that Goldsmith, whose campaign was condemned by his sister, Jemima Khan, may soon publicly repent.

In recent days, the new mayor Khan has also spoken by phone to his predecessor Boris Johnson, who advised him to learn from his errors and not to rush executive appointments (five senior figures either resigned or were fired during Johnson’s first year in City Hall). Khan is expected to make Andrew Adonis, the cerebral former transport secretary (and his old boss), his deputy mayor for transport, even though Adonis was a prominent supporter of Khan’s main rival for the Labour mayoral nomination, Tessa Jowell. He has also retained the team that won him his landslide victory, including Patrick Hennessy (communications), David Bellamy (chief of staff), Jack Stenner (political strategy), Nick Bowes (policy) and Leah Kreitzman (external affairs and international relations). The transition is being overseen by Neale Coleman, a former Livingstone and Johnson aide, who resigned recently as Jeremy Corbyn’s director of policy.

Khan’s team says that he will make a “fast start” on implementing his manifesto pledges. In his first 100 days, he will establish Homes for Londoners, a new authority to oversee housebuilding, launch a review of the capital’s security and play a pivotal role in the EU referendum campaign. His new one-hour “Hopper” fare, allowing bus passengers to make additional journeys for free, will be introduced in September.

As well as the anti-Trump, many in Labour hope that Khan will be the anti-Corbyn. His personal mandate (five times greater than the party leader’s) makes him a rival figure of authority. Corbyn’s opponents have hailed the mayor’s inclusive and pro-business campaign as a masterclass in winning. “We’re all Khanites now!” declared former deputy leader Harriet Harman outside the PLP meeting on 9 May.

When the mayor addressed the gathering, he received a minute-long standing ovation. In his remarks, he delivered a series of implicit rebukes to the party leadership (he had met Jeremy Corbyn for a face-to-face meeting just an hour earlier). “When we win, we can change lives for the better. There is no such thing as glorious defeat,” he declared, advocating a “big tent” approach that “appeals to everyone in our country, regardless of their background”. “We lose when we take an ‘us and them’ approach.”

Khan’s landslide victory and the unseasonably warm weather in London that accompanied it have stirred memories of the party’s 1997 general election triumph among some Labour insiders. “A lot of the party HQ staff [whom Khan addressed before the PLP] are very young and they’ve never experienced a victory before,” one told me. “It’s important for them to realise that you can win and this is how you do it.”

***

In a stunt conceived too late for the campaign, Khan’s team considered running two adverts on the side of vans: one in red, bearing the message “Sadiq Khan: hope”; and the other in blue, stating “Zac Goldsmith: fear”. It is the triumph of the former over the latter that makes the London mayor’s victory so potent. At a time when many weave a dystopian narrative of decline, the anti-Trump has proved that optimism can be vindicated.

For nearly a decade, commentators have debated when, or if, the United Kingdom would enjoy its “Obama moment”. The election of Khan, the son of working-class Pakistani immigrants who grew up as one of eight children in a council house, is by some distance the closest it has come. There are few political figures with a story as emotionally resonant as his.

As Barack Obama prepares to depart from the White House, to be replaced by the demagogic Donald Trump or the technocratic Hillary Clinton, it feels fitting that, here in Britain, another progressive politician should take on the mantle of hope.