-1

Why 'then' and 'catch' is both called if I add callback function?

function sendMail(data, callback) {

    sgMail
        .send(data)
        .then(() => {
            console.log('Email sent');
            callback(true);
        })
        .catch((error) => {
            console.error(error);
            callback(false);
        })
}

I'm sorry if its duplicate I just cant find an answer.

1 Answers1

1

catch() will run if code in a previous then() throws an error.

Take this example:

const promise = new Promise((resolve) => {
  resolve({ data: true })
})

promise.then(() => {
    console.log('Email sent');
    throw new Error("throw an error")
})
.catch((error) => {
    console.error(error);
    console.log('Error was thrown in then() clause');
})

The promise resolve successfully, then() executes until it throws an error, then catch is run because an error was thrown.


However this example never runs the catch() because no error is ever thrown.

    const promise = new Promise((resolve) => {
      resolve({ data: true })
    })

    promise.then(() => {
        console.log('Email sent');
    })
    .catch((error) => {
        console.error(error);
        console.log('Error was thrown in then() clause');
    })
Alex Wayne
  • 178,991
  • 47
  • 309
  • 337