非同期Calback


Javascript is synchronous.
JavaScriptは同期されています.起動後から同期運転を開始します.
(シースは、宣言された関数または変数が範囲の上部にある)
シンクロコールバック
JAvascriptエンジンは、宣言されたprintImmedialyを上部に移動し、コードを順次実行します.

ひどうきコールバック
非同期関数もハイライトされ、上部で宣言され、順次実行されます.
パッケージsettimeoutのprintWithDelayを作成しました.

Callback地獄体験

// Callback hell example

class UserStorage {
  loginUser(id, password, onSuccess, onError) {
    setTimeout(() => {
      if (
        (id === 'ellie' && password === 'dream') ||
        (id === 'corder' && password === 'academy')
      ) {
        onSuccess(id);
      } else {
        onError(new Error('not found'));
      }
    }, 2000);
  }
  getRoles(user, onSuccess, onError) {
    setTimeout(() => {
      if (user === 'corder') {
        onSuccess({ name: 'gichoel', role: 'admin' });
      } else {
        onError(new Error('no access'));
      }
    }, 1000);
  }
}

const userStorage = new UserStorage();

const id = prompt('enter your id');
const password = prompt('enter your password');

userStorage.loginUser(
  id,
  password,
  (user) => {
    userStorage.getRoles(
      user,
      (userWithRole) => {
        alert(
          `Hello ${userWithRole.name}, you have a ${userWithRole.role} role`,
        );
      },
      (error) => {
        console.log(error);
      },
    );
  },
  (error) => {
    console.log(error);
  },
);