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

194
Vistas
How to catch a rejected promises in same time order as resolves?

Promises which resolve() or reject() can be handled in order with .then() regardless if they are resolved or rejected:

const getRecordById = (id) => {
    return new Promise((resolve, reject) => {
        const randNum = Math.floor(Math.random() * 2) + 1;
        if (randNum === 1) {
            resolve({ id, firstName: 'John', lastName: 'Doe' });
        } else {
            reject(`user id ${id} not found`);
        }
    });
};

for (let id = 1; id <= 10; id++) {
    getRecordById(id)
        .then(
            (record) => { console.log(`you got record #${record.id}`); },
            (errMessage) => { console.log(`error was: ${errMessage}`); }
        );
}

enter image description here

But I read in articles like this one that e.g.

many libraries and frameworks assume that promises are always rejected with an error

and so one should instead reject with an error like this: reject(new Error('Oops!')); instead of rejecting with a string.

But when I reject with an Error object, why do all the rejections complete after the resolves?

const getRecordById = (id) => {
    return new Promise((resolve, reject) => {
        const randNum = Math.floor(Math.random() * 2) + 1;
        if (randNum === 1) {
            resolve({ id, firstName: 'John', lastName: 'Doe' }); 
        } else {
            reject (new Error(`user id ${id} not found`)); 
        }
    });
};

for (let id = 1; id <= 10; id++) {
    getRecordById(id)
        .then((record) => { console.log(`you got record #${record.id}`); })
        .catch((errMessage) => { console.log(`error was: ${errMessage}`); });
}

enter image description here

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

In the second example the errors are shown at the bottom is not because reject was an error object. In the first code you have handled error inside .then but in the second code snippet there is .catch for handling exception. Second code will log in same order as first if you handle error inside .then.

const getRecordById = (id) => {
    return new Promise((resolve, reject) => {
        const randNum = Math.floor(Math.random() * 2) + 1;
        if (randNum === 1) {
            resolve({ id, firstName: 'John', lastName: 'Doe' }); 
        } else {
            reject (new Error(`user id ${id} not found`)); 
        }
    });
};

for (let id = 1; id <= 10; id++) {
    getRecordById(id)
        .then((record) => { console.log(`you got record #${record.id}`)},
            (errMessage) => { console.log(`error was: ${errMessage}`); })
}

about 4 years ago · Juan Pablo Isaza Denunciar
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