Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

129
Visualizações
Recursive async function returns undefined

I have a JavaScript function that is supposed to take in person's first and last name and generate a unique abbreviation. Examples:

Michael Scott -> scmi1
Michelle Scrambledeggs -> scmi2
Genghis Khan -> khge1

Inside this function, I nested a recursive function that is supposed to find a suffix number that is not taken, but I can't get it to return proper value. Here's the code:

    /**
     * Generates a abbreviation from customer's first and last name
     * by combining last name's first two letter with first name's first two letters
     * @param {string} firstName
     * @param {string} lastName
     * @returns {string} abbreviation, for example person named John Smith will have short: 'smjo1'
     */
    const generateShort = async (firstName, lastName) => {
        // Concatenate last name's two first letters with first name's two first letters
        var short = lastName.substring(0, 2) + firstName.substring(0, 2)
        short = short.toLowerCase()

        // At the end of each short, add a number
        // So that each abbreviation can be unique
        async function findFreeSuffix(suffix_number) {
            var final_short = short + suffix_number

            // Scan the database in search for person with this short
            window.api.searchClientExact(final_short).then(res => {
                if (res.length > 0) {
                    // If this abbreviation is taken...
                    findFreeSuffix(suffix_number + 1)
                } else {
                    console.log(suffix_number) // <- This prints the correct result, but I'm unable to return it
                    return suffix_number
                }
            })
        }

        const suffix = await findFreeSuffix(1)

        // Suffix is undefined :(
        return short + suffix
    }
about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda