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

134
Views
Best way to handle recursion with async functions and promises?

The following is pseudocode to illustrate my problem. The parent function must ultimately return a promise when all of the tasks are done (I've omitted the others for clarity). The parent function calls child functions and some of the child functions have to perform their tasks recursively and so, for clarity, I've separated them into worker functions. If there is a cleaner way I would love to learn it.

How best to handle the recursion in this example?

// This function must ultimately return a Promise.
async function parentFunction(uId) {
    try {
        await childFunction(uId);
        return Promise.resolve(uId);
    } catch (error) {
        console.log(error);
    }
}

async function childFunction(uId) {
    try {
        const done = await workerFunction(uId);

        if (done) {
            return Promise.resolve(true);
        } else {
            // There are more files to delete; best way to handle recursion?
        }
    } catch (error) {
        console.log(error);
    }
}

async function workerFunction(uId) {
    try {
        // Query the database, limit to 100 files.
        const query = await db.queryFiles().limit(100);

        if (query.size == 0) {
            // Nothing to delete, we're done!
            return Promise.resolve(true);
        }

        // Perform an atomic (all-or-none) batch delete that can only take 100 files at most.
        await db.batchDelete(query);
        
        // Batch delete successfull!
        if (query.size < 100) {
            // The query was less than 100 files so there can be no more files to delete.
            return Promise.resolve(true);
        } else {
            // There may possibly be more files to delete.
            // Return a promise or handle recursion here?
            return Promise.resolve(false);
        }
    } catch (error) {
        console.log(error);
    }
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

just do recursion it's fine!

async function deleteFiles() {
  const query = await db.queryFiles().limit(100)
  if (query.size > 0) {
    await db.batchDelete(query)
  }
  if (query.size === 100) {
    return deleteFiles()
  }
  return true;
}
about 4 years ago · Juan Pablo Isaza Report
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!