How is 'return new Error' different from 'throw'

69 views Asked by At

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.

0

There are 0 answers