0

I was practicing promise and this exercise popped up. I knew the throw will immediately hop out of the the function and find the nearest .catch. However, I still don't understand why return new Error('test'); is followed by the action of .then and not .catch.

Code snippet

function job(state) {
    return new Promise(function(resolve, reject) {
        if (state) {
            resolve('success');
        } else {
            reject('error');
        }
    });
}

let promise = job(true);

promise

.then(function(data) {
    console.log(data);

    return job(true);
})

.then(function(data) {
    if (data !== 'victory') {
        throw 'Defeat';
    }

    return job(true);
})

.then(function(data) {
    console.log(data);
})

.catch(function(error) {
    console.log(error);

    return job(false);
})

.then(function(data) {
    console.log(data);

    return job(true);
})

.catch(function(error) {
    console.log(error);

    return 'Error caught';
})

.then(function(data) {
    console.log(data);

    return new Error('test');
})

.then(function(data) {
    console.log('Success:', data.message);
})

.catch(function(data) {
    console.log('Error:', data.message);
});

The result

> "success"
> "Defeat"
> "error"
> "Error caught"
> "Success:" "test"

I have researched but I can't seem to find any explanation on this matter. I also consulted chatGPT but it really sucked.

4
  • 1
    The difference is: when you are returning an Error, you are keeping the stacktrace operating normally. But when you throw an Error, it travels up the stacktrace until being caught (Promise implicitly catches the error) Commented Dec 14, 2023 at 14:57
  • 2
    Returning an Error is no different than returning an Object or a string or something - it's just some data. Yeah, you explicitly call it an Error, but since you aren't telling Javascript to treat it as such it just assumes your method actually needed to return that. Like, what if your promise is something like ResolveToErrorMessage, would you expect it to resolve in the catch block? It's kind of stupid, but it keeps things versatile enough. Commented Dec 14, 2023 at 15:11
  • Can you please be more specific on "stacktrace operating normally"? I thought Promise implicitly catches the error long as the Error occurs Commented Dec 14, 2023 at 16:02
  • @LamMyKy-Kailey Point is there is no error (exception) occurring. It's just an object that is being created, until it is thrown - but it isn't. Commented Dec 14, 2023 at 16:09

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.