I want to do something simple: I want my function to return a promise(1). This promise(1) will use another promise(2) to perform a task. Promise(2) is chained to multiple then/catch steps. Inside those steps, promise(1) may need to be resolved/rejected. The chain of promise(2) needs to stop executing as now promise(1) is resolved/rejected and should stop running.
What's the best way to do this?
See the following example code:
function performDiv(a, b) {
return new Promise(function (res, rej) { // promise(2)
if (b === 0) {
return rej(new Error('div by 0'));
}
res(a / b);
})
}
function div(a, b) {
return new Promise(function (res, rej) { // promise(1)
performDiv(a, b)
.then(res) // <--- HERE I want to break the chain
.catch(rej) // <--- OR HERE, if there's a problem
.then(function () {
console.log('I don\'t want this to be shown')
});
});
}
div(10, 2)
.then(function (result) {
console.log(result);
})
.catch(function (err) {
console.log(err);
});
Currently, the I don't want this to be shown
(a hypothetical next step in order to resolve the promise(1)) is shown while I want to find a solution where it isn't, as the promise(1) is already resolved/rejected.