LoginSignup
15
15

More than 5 years have passed since last update.

非同期の例外処理する時に jQuery.Deferred を使う

Posted at

よくある例外処理

try
  myfunc()
catch e
  console.log "Error:", e

ここで myfunc() の中でAjaxなどの非同期処理がある場合、その戻り値次第で例外を発生させたい場合があるが、これではキャッチできない。

こういう時は jQuery.Deferred を使う。
myfunc

myfunc: () ->
  d = new $.Deferred

  # Ajaxでなにか呼び出して結果をcallbackに格納
  $.get "/nanika", (callback) -> 
    if callback == 200
      # 成功
      d.resolve()
    else
      # 例外
      d.reject()

  return d.promise()

こんな感にしておけば

promise = myfunc()
promise.done ->
  # 成功した場合の処理
promise.fail ->
  # 失敗した場合の処理

と書ける。
あと resolve(), reject() はそれぞれ引数を持つことが出来、done(), fail() がそれを受け取る。

15
15
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
15
15