Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

306
Visualizações
Code throwing unhandled rejection error when running promise

I am trying to write a Javascript promise that resolves and rejects the desired variables. I am getting the error message below after running in the console

[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch().
 code: 'ERR_UNHANDLED_REJECTION'

Here is my code

Js File:


const grimeUserLeft = false;
const userWatchingGrimeVids = true;

let grimePromise = new Promise((resolve, reject) => {
  if (grimeUserLeft) {
    reject("User Left");
  } else if (userWatchingGrimeVids) {
    reject("This user is a G");
  } else {
    resolve("Congrats. Your channel doesn't suck");
  }
});

grimePromise.then((message) => {
  console.log("Success: " + message);
});
grimePromise.catch((message) => {
  console.log("You Failed: " + message);
});

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

By calling the .then() and the .catch() handler on two different places, you actually end up with two different promises - each of .then() and .catch() returns a new one. The promise returned by .then() will not be caught by the separate .catch() handler:

const grimeUserLeft = false;
const userWatchingGrimeVids = true;

let grimePromise = new Promise((resolve, reject) => {
  if (grimeUserLeft) {
    reject("User Left");
  } else if (userWatchingGrimeVids) {
    reject("This user is a G");
  } else {
    resolve("Congrats. Your channel doesn't suck");
  }
});

grimePromise
  .then((message) => {
    console.log("Success: " + message);
  })
  .catch(() => console.log(1));

grimePromise.catch((message) => {
  console.log(2);
  console.log("You Failed: " + message);
});

Therefore, one promise gets turned into two. Each of them will adopt the state of the original promise. When the original is rejected, both the derived promises reject. Yet only one is handled.

Instead, you can directly specify the .catch() in the same promise chain as the .then():

const grimeUserLeft = false;
const userWatchingGrimeVids = true;

let grimePromise = new Promise((resolve, reject) => {
  if (grimeUserLeft) {
    reject("User Left");
  } else if (userWatchingGrimeVids) {
    reject("This user is a G");
  } else {
    resolve("Congrats. Your channel doesn't suck");
  }
});

grimePromise
  .then((message) => {
    console.log("Success: " + message);
  })
  .catch((message) => {
    console.log("You Failed: " + message);
  });
<h1>Check the browser console - no unhandled promise rejections</h1>

Or alternatively, specify both handlers in the then():

const grimeUserLeft = false;
const userWatchingGrimeVids = true;

let grimePromise = new Promise((resolve, reject) => {
  if (grimeUserLeft) {
    reject("User Left");
  } else if (userWatchingGrimeVids) {
    reject("This user is a G");
  } else {
    resolve("Congrats. Your channel doesn't suck");
  }
});

grimePromise
  .then(
    (message) => {
      console.log("Success: " + message);
    },
    (message) => {
      console.log("You Failed: " + message);
    }
  );
<h1>Check the browser console - no unhandled promise rejections</h1>

about 4 years ago · Juan Pablo Isaza Relatório

0

The reason this isn't working is because you didn't have a .catch() on the first one. It was throwing a rejection, but you weren't handling it gracefully with a catch, so it threw.

Here is your code working - I just moved your catch block to go after the .then:

const grimeUserLeft = false;
const userWatchingGrimeVids = true;

const grimePromise = new Promise((resolve, reject) => {
    if (grimeUserLeft) {
        reject('User Left');
    } else if (userWatchingGrimeVids) {
        reject('This user is a G');
    } else {
        resolve("Congrats. Your channel doesn't suck");
    }
});

grimePromise
    .then((message) => {
        console.log('Success: ' + message);
    })
    .catch((message) => {
        console.log('You Failed: ' + message);
    });

Just as a tip though, you should only reject whenever the function is unsuccessful in some way. That could be a timeout, a network error, incorrect input etc. Whatever is inside of a reject should ideally be an error.

Additionally, I'd recommend using async await, as it's much easier to read and more manageable. You can easily do this by creating a function which returns your new Promise, then awaiting it like so:

const grimeUserLeft = false;
const userWatchingGrimeVids = true;

const grime = () => {
    return new Promise((resolve, reject) => {
        if (grimeUserLeft) {
            reject(new Error('User Left'));
        } else if (userWatchingGrimeVids) {
            resolve('This user is a G');
        } else {
            resolve("Congrats. Your channel doesn't suck");
        }
    });
};

const doStuff = async () => {
    try {
        const result = await grime();
        console.log(result);
    } catch (error) {
        console.error(error);
    }
};

doStuff();

To make this truly asynchronous, you should ideally be doing some async stuff inside of the promise. This can be demonstrated with a setTimeout:

const grimeUserLeft = false;
const userWatchingGrimeVids = true;

const grime = () => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (grimeUserLeft) {
                reject(new Error('User Left'));
            } else if (userWatchingGrimeVids) {
                resolve('This user is a G');
            } else {
                resolve("Congrats. Your channel doesn't suck");
            }
        }, 2000);
    });
};

const doStuff = async () => {
    try {
        const result = await grime();
        console.log('result finished after 2 seconds');

        console.log(result);
    } catch (error) {
        console.error(error);
    }
};

doStuff();

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda