简体   繁体   中英

How to use IcedCoffeeScript in function with two callbacks?

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 ?

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

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM