LoginSignup
3
2

More than 5 years have passed since last update.

必須ではない非同期処理を行う場合のTips

Posted at

例えば次のような処理です。

// ログイン処理

// データ検索処理

ログイン処理の結果によらずデータ検索処理は行うものとします。ただしログイン処理は非同期処理です。

こんな感じのコードが思いつきますが、同じ処理があるのはよくありません。

if (login) {
User.login.execute()
  .then(function() {
    Data.Search.execute();
  })
} else {
  Data.Search.execute();
}

そこでPromiseを使います。

function loginFunction() {
  return new Promise(funciton(res, rej) {
    if (login) {
      User.login.execute()
        .then(function() {
          res();
        })
    }else{
      res();
    }
  })
}

loginFunction()
  .then(function() {
    Data.Search.execute();
  })

Promise = 非同期処理で有効ですが、非同期じゃない場合も含めてラッピングできるのが便利です。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2