Skip to content

Instantly share code, notes, and snippets.

@1isten
Last active June 9, 2020 19:32
Show Gist options
  • Save 1isten/b91b12765d37ad659c7aea2969a0cdd1 to your computer and use it in GitHub Desktop.
Save 1isten/b91b12765d37ad659c7aea2969a0cdd1 to your computer and use it in GitHub Desktop.
the only way to early break Promise .then() chain is to make the code fall into .catch()
const myLimit = 3;
function checkLimit(data) {
if (data === myLimit) {
const err = new Error('let me exit!');
err.data = `${data} is the enough!!!`;
throw err; // or, return Promise.reject(err)
}
}
function asyncAddOne(data) {
const hardLimit = 10;
return new Promise((resolve, reject) => {
setTimeout(() => {
const result = Number.isNaN(data + 1) ? 0 : data + 1;
const err = new Error('stop!');
err.data = `${result} is enough.`;
result < hardLimit ? resolve(result) : reject(err);
}, 1000);
});
}
(function() {
const init = 0;
asyncAddOne(init)
.then(data1 => { // 1
console.log('data1:', data1);
checkLimit(data1);
return asyncAddOne(data1);
})
.then(data2 => { // 2
console.log('data2:', data2);
checkLimit(data2);
return asyncAddOne(data2);
})
.then(data3 => { // 3
// return console.log('data3:', data3) won't break the .then() chain
// instead it just makes the data4 become undefined
// since the asyncAddOne handles NaN, the data5 will become 0
// and the the code will keep going
// data4: undefined, data5: 0, data6: 1, data7: 2, data8: 3, exit
console.log('data3:', data3);
checkLimit(data3); // the only way to break the .then() chain is to throw an error or return a Promise rejection to make the code fall into the .cache() handler
return asyncAddOne(data3);
})
.then(data4 => { // 4
console.log('data4:', data4);
checkLimit(data4);
return asyncAddOne(data4);
})
.then(data5 => { // 5
console.log('data5:', data5);
checkLimit(data5);
return asyncAddOne(data5);
})
.then(data6 => { // 6
console.log('data6:', data6);
checkLimit(data6);
return asyncAddOne(data6);
})
.then(data7 => { // 7
console.log('data7:', data7);
checkLimit(data7);
return asyncAddOne(data7);
})
.then(data8 => { // 8
console.log('data8:', data8);
checkLimit(data8);
return asyncAddOne(data8);
})
.then(data9 => { // 9
console.log('data9:', data9);
checkLimit(data9);
return asyncAddOne(data9);
})
.then(data10 => { // ✋unreachable
console.log('data10:', data10);
})
.catch(error => {
console.error(error.message, error.data); // stop! 10 is enough.
});
})();
@1isten
Copy link
Author

1isten commented Jan 1, 2020

OUTPUT >>>

data1: 1
data2: 2
data3: 3
let me exit! 3 is the enough!!!

if myLimit is set to 10 or greater than 10:

data1: 1
data2: 2
data3: 3
data4: 4
data5: 5
data6: 6
data7: 7
data8: 8
data9: 9
stop! 10 is enough.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment