Early exit from a javascript promise

Maybe create custom error type that signals an early exit?

class ExitEarly extends Error {
    constructor(message) {
        super(message);
        this.name = "ExitEarly";
    }
}

firstPromise.then(result => {
    if (/* time to exit early for whatever reason */) {
        throw new ExitEarly('Exiting after firstPromise');
    }
    return secondPromise(result);
})
.then(result2 => {
    if (/* time to exit early for whatever reason */) {
        throw new ExitEarly('Exiting after secondPromise');
    }
    return thirdPromise(result2);
})
.then(result3 => {
    return lastPromise(result3);
})
.catch(err => {
    if (err instanceof ExitEarly) {
        // handle early exit gracefully
    } else {
        // handle real errors
        console.log(err); 
    }
});

This way, you can differentiate it from actual errors in your catch block?

1 Like