How to use IcedCoffeeScript in a function with two callbacks?

Suppose I have a function like this (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 the use of this function in IcedCoffeeScript with await and defer ?

+4
source share
2 answers

I don’t think there is an optimal way to do this in ice coffee script, although there are some interesting suggestions in this post: Iced coffee script with several callbacks

I would just stick with a vanilla coffee script:

So your function would be indecent in a coffee script

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

and as you might call it in a coffee script

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

If you can rewrite the fun function in the style of "errback" (err, result) in a coffee script, it will be:

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

you would use it just like in frozen coffeescript

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

From maxtaco / coffee- script # 120 :

There are two main ways to solve this problem:

  • Create 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 ice.Rendezvous lib (sample code 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
source

Source: https://habr.com/ru/post/1500549/


All Articles