Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

128
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda