Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

127
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!