-2

I have experience in JavaScript and I am used to callbacks functions:

function myFun(arg1, arg2, successCB, failCB) {
  var sum = arg1 + arg2;
  if (sum > tooHigh) {
    failCB("too high!");
  } else {
    otherFun(sum, arg1, successCB, failCB);
  }
}

I can write the same code in Erlang:

my_fun(Arg1, Arg2, SuccessCB, FailCB) ->
  case Arg1 + Arg2 of
    Sum when Sum > ?TOO_HIGH ->
      FailCB(too_high);
    Sum ->
      other_fun(Sum, Arg1, SuccessCB, FailCB)
  end.

I find this approach reasonable from my experience, but I feel like I will need to do a lot of this in my code, so, apparently, there is a better way to manage these true/false/whatever scenarios.

Is this typical Erlang code? Is there some other way that I should be doing this?

Nathaniel Waisbrot
  • 23,261
  • 7
  • 71
  • 99
Sergei Basharov
  • 51,276
  • 73
  • 200
  • 335
  • Why not just use different function clauses? Or `case User of`? – A. Sarid Aug 08 '16 at 07:15
  • 3
    You need to do your homework, since if you're trying to use the same approach to error handling in Erlang as you do in other languages, you're doing it wrong. Try searching for the Erlang "let it crash" philosophy, for example, and [here's a related question](http://stackoverflow.com/questions/4393197/erlangs-let-it-crash-philosophy-applicable-elsewhere). – Steve Vinoski Aug 08 '16 at 11:23

1 Answers1

0

JavaScript uses callbacks because you have a single thread and callbacks are the way that you transfer your state across context switches.

Callback functions are a generally-useful tool, but in JavaScript they're a fundamental tool because it's how asynchronous work gets done.

In Erlang, you can (and should!) use many processes. Within a single process, you can make synchronous, blocking calls because this doesn't affect system performance.

I'd expect the Erlang version of the above JS code to look like

my_fun(Arg1, Arg2) ->
  case Arg1 + Arg2 of
    Sum when Sum > ?TOO_HIGH ->
      too_high;
    Sum ->
      other_fun(Sum, Arg1)
  end.

There's no callbacks, because the functions return the values (too_high and maybe {ok, Result}). All the functions are blocking -- if other_fun is a network call, it might wait several seconds before returning. If parallelism is needed, you spawn as many processes as you like.

Nathaniel Waisbrot
  • 23,261
  • 7
  • 71
  • 99