0

I wondering if we can set a function containing a Callback function as parameter to another function who takes a callback too. Example

function save(err, data, cb){};

function get(id, cb){};

get('12', save)?

poulo
  • 55
  • 5

2 Answers2

0

Of course, a variable can be passed as argument of a function! It may be clearer for you if you do:

// This also works with the notation `function save(...)`
var save = function(err, data, cb) {
        alert('save' + err); // save12
    },
    get = function(id, cb) {
        alert('get' + id); // get12
        cb(id); // This call the "save" function
    }
;

get('12', save);

Just be careful to not stack your callback too much or you will enter in the callback hell world!

Community
  • 1
  • 1
Gnucki
  • 5,043
  • 2
  • 29
  • 44
0

Yes you can, check this example:

jsFiddle Example

    jQuery(document).ready(function () {   
  function1({
       param: "1",
       callback: function () {
           function2({
               param : "2",
               callback: function(){
                   alert("hello");
               }
           })
       }
    });    
});

function function1(params){
    alert(params.param);
    params.callback();
}

function function2(params){
    alert(params.param);
    params.callback();
}

I hope it will be useful.

Carlo G.
  • 162
  • 12