How to use IcedCoffeeScript in function with two callbacks?

428 views Asked by At

Let's assume I have such function (in Javascript):

function fun(success_cb, error_cb) {
  var result;
  try {
    result = function_that_calculates_result();
    success_cb(result);
  } catch (e) {
    error_cb(e);
  }
}

And I use it like:

fun(function(result) {
  console.log(result);
}, function(error) {
  console.log(error.message);
});

How can I rewrite usage of this function in IcedCoffeeScript with await and defer?

2

There are 2 answers

0
doublerebel On

From maxtaco/coffee-script#120:

There are two main ways to solve this issue:

  1. Build a connector (as suggested by maxtaco):
converter = (cb) ->
  cb_success = (args...) -> cb null, args...
  cb_error = (err) -> cb err
  return [cb_error, cb_success]

await getThing thing_id, converter(defer(err,res))...
console.log err
console.log res
  1. Use the iced.Rendezvous lib (code sample from node-awaitajax):
settings.success = rv.id('success').defer data, statusText, xhr
settings.error   = rv.id('error').defer xhr, statusText, error
xhr = najax settings

await rv.wait defer status
switch status
   when 'success' then defersuccess data, statusText, xhr
   when 'error' then defererror xhr, statusText, error
0
saintmac On

I don't think there is an optimal way to do that in iced coffee script, although that post has some interesting suggestions: Iced coffee script with multiple callbacks

I would just stick to vanilla coffee script:

This is how your function would be writtent in coffee-script

fun = (success_cb, error_cb) ->
  try
    result = function_that_calculates_result()
    success_cb result
  catch e
    error_cb e

and how you would call it in coffee script

fun (result) ->
  console.log result
, (error) ->
  console.log error.message

If you can rewrite the fun function in an "errback" style (err, result) in coffee script, that would be:

fun = (callback) ->
  try
    result = function_that_calculates_result()
    callback null, result
  catch e
    callback e

you would then use it like that in iced coffeescript

await fun defer error, result
if error
  console.log error.message
else
  console.log result