JavaScriptのクラスのexecutorの挙動が分からない

前提

以下のコードで、SimpleAsyncTaskというクラスを生成し、成功かどうかによってresolveとrejectに処理を分岐しています。
その処理によって、コンソールに「成功」と出るか、エラーを投げるかに分かれます。

発生している問題・エラーメッセージ

挙動としては、ちゃんと動いています。
問題は、なぜこれが動くのか分からないのです。
成功の場合だと仮定すると、
① const task = new SimpleAsyncTask((resolve, reject) => ...... でインスタンス化された瞬間に、setTimeoutが実行される
② successがtrueになり、resolveが呼ばれ引数は"成功"

const resolve = (value) => {
if (this.onSuccess) {
this.onSuccess(value);
}
};
resolveの宣言はここであるが、this.onSuccessはnullに設定されているのでこのif内はfalseになり、この先何も起こらない

と考えてしまうのです。
実際はちゃんと動いているので私が間違っているのですが、
このコードがどういう順で動いているのか、どなたか順を追って説明していただけませんか?

該当のソースコード

JavaScript

1class SimpleAsyncTask {2 constructor(executor) {3 this.onSuccess = null;4 this.onFailure = null;5 6 const resolve = (value) => {7 if (this.onSuccess) {8 this.onSuccess(value);9 }10 };11 12 const reject = (reason) => {13 if (this.onFailure) {14 this.onFailure(reason);15 }16 };17 18 executor(resolve, reject);19 }20 21 then(onSuccess) {22 this.onSuccess = onSuccess;23 return this;24 }25 26 catch(onFailure) {27 this.onFailure = onFailure;28 return this;29 }30}31 32const task = new SimpleAsyncTask((resolve, reject) => {33 setTimeout(() => {34 const success = Math.random() > 0.5; // 50% の確率で成功または失敗35 if (success) {36 resolve("成功!");37 } else {38 reject("失敗...");39 }40 }, 500);41});42 43task 44 .then((result) => {45 console.log(result);46 })47 .catch((error) => {48 console.error(error);49 });50

コメントを投稿

0 コメント