I can't find out how to make a function that calls another function at the end.
I want to be able to do something like this:
book.save (err) ->
MyFunc param1, param2, (callbackParam) ->
# some code using callbackParam
MyFunc = (param1, param2) ->
# some other code that defines callbackParam
?.call(callbackParam)
What has to be called and how does it receive the data?
A custom callback function can be created by using the callback keyword as the last parameter. It can then be invoked by calling the callback() function at the end of the function. The typeof operator is optionally used to check if the argument passed is actually a function. console.
You can simply invoke a function by placing parenthesis after its name as shown in the following example. // Generated by CoffeeScript 1.10. 0 (function() { var add; add = function() { var a, b, c; a = 20; b = 30; c = a + b; return console. log("Sum of the two numbers is: " + c); }; add(); }).
For example: In Node. js, when a function start reading file, it returns the control to execution environment immediately so that the next instruction can be executed. Once file I/O gets completed, callback function will get called to avoid blocking or wait for File I/O.
In simple language, If a reference of a function is passed to another function as an argument to call it, then it will be called as a Callback function. In C, a callback function is a function that is called through a function pointer. In C++ STL, functors are also used for this purpose.
If you want to call MyFunc
as:
MyFunc param1, param2, some_function
Then it should look like this:
MyFunc = (param1, param2, callback) ->
# some code that defines callbackParam
callback callbackParam
And if you want to make the callback
optional:
MyFunc = (param1, param2, callback) ->
# some code that defines callbackParam
callback? callbackParam
And if you want to supply a specific @
(AKA this
), then you'd use call
or apply
just like in JavaScript:
MyFunc = (param1, param2, callback) ->
# some code that defines callbackParam
callback?.call your_this_object, callbackParam
The (callbackParam) -> ...
stuff is just a function literal that acts like any other parameter, there's no special block handling like in Ruby (your tags suggest that Ruby blocks are the source of your confusion).
Here's a cleaner, easier to read and understand example:
some_function = (callback) ->
param1 = "This is param1"
param2 = "This is param2"
callback(param1, param2)
callback = (param1, param2) ->
console.log(param1)
console.log(param2)
@tester = ->
some_function(callback)
"done"
Now load your website, go to the console, and call the function:
> tester()
This is param1
This is param2
< "done"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With