jbr / sibilant

Just another compile-to-js LISP-like language
https://sibilant.org
MIT License
386 stars 47 forks source link

How to define asynchronous function callbacks #82

Closed gamecubate closed 8 years ago

gamecubate commented 8 years ago

I'm not clear on how to define asynchronous function callbacks. I tried the function (got-data) below but that doesn't work (never gets invoked).

;;; Data file path
(var *CSV* "spots.csv")

;;; Fetch data (using d3's asynchronous CSV file fetcher)
(d3.csv *CSV* got-data)

;;; callback
(def got-data (err data)
  (if err
    (throw err)
    (console.log (JSON.stringify data))))

Thanks in advance.

jbr commented 8 years ago

Hi! Looks like it's a matter of definition order to me. Although javascript allows "hoisting" of variables, sibilant intentionally does not support hoisted functions. This means that the definition of got-data needs to be above the first use thereof, like this:

;;; Data file path
(var *CSV* "spots.csv")

;;; callback
(def got-data (err data)
  (if err
    (throw err)
    (console.log (JSON.stringify data))))

;;; Fetch data (using d3's asynchronous CSV file fetcher)
(d3.csv *CSV* got-data)

Alternatively, you could define it anonymously, as follows:

(d3.csv "spots.csv" (#(err data)
  (if err
    (throw err)
    (console.log (JSON.stringify data)))))
gamecubate commented 8 years ago

Thanks. I had figured as much in the meantime, though was surprised because I had for some (odd) reason thought that definition order did not matter.