js nested promise test - NaClYen/blog GitHub Wiki
最近想讓大量串接的 Promise 可以及時中斷, 到處寫 if(xxx) return XXX
又太阿雜, 就試試看類似 try-catch 的框架, 可行!
class NestedPromiseTest {
canceled = false;
check() {
if (this.canceled) return Promise.reject("canceled");
}
async go_1() {
this.check();
console.log("end of go_1");
}
async go_2() {
await this.check(); // 差在是否 await check
console.log("end of go_2");
}
}
var test = new NestedPromiseTest();
test.go_1(); // output: end of go_1
test.go_2(); // output: end of go_2
test.canceled = true;
test.go_1(); // output: end of go_1 & Uncaught (in promise) canceled
test.go_2(); // output: Uncaught (in promise) canceled
test.go_1().catch((err) => console.warn(`error catched: ${err}`)); // output: end of go_1 & Uncaught (in promise) canceled
test.go_2().catch((err) => console.warn(`error catched: ${err}`)); // output: error catched: canceled