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

141
Views
Catching promise errors from a loop

I need to call multiple promises inside a for loop, but it gives me unhandled promise exception during each run. The way to solve this is to return the second promise, this way the last catch would be executed and it would work without errors, but - second and more iterations would not be executed.

const doFirstThing = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => (resolve(['a', 'b', 'c'])), 1000);
    });
}

const doSecondThing = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => (reject('test')), 500); // reject here
    });
}

doFirstThing()
.then(results => {
    results.forEach(result => {
        doSecondThing(result)
        .then(() => console.log(result, 'done'));
    });
})
.catch(error => console.log(error));

How can I deal with this?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

To prevent unhandled promise exception chain .catch() to lat .then(); substitute using Promise.all() and .map() for .forEach()

const doFirstThing = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => (resolve(['a', 'b', 'c'])), 1000);
    })
}

const doSecondThing = (r) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => (reject('test')), 500); // reject here
    })
}

doFirstThing()
.then(results => {
    return Promise.all(results.map(result => {
        return doSecondThing(result)
    }));
})
.then((result) => console.log(result, 'done'))
.catch(error => console.log(`err:${error}`));

over 4 years ago · Santiago Trujillo 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!