How to execute a function whose name was passed as parameter of another function, à the callback?

2

I created this function in order to abstract the $.ajax() calls to be executed at several different times. One of its parameters is the name of one of the functions that I would like it to run on success.

However, how should I call this "callback"?

function submitData(myCallback) {
    $.ajax({
        success: function(res){
            myCallback(res);
        }
    });

}

function processarResponse(response) {

}

Finishing with the help received from Valdeir Psr: Passing the parameter 'myCallback' must be done by passing the name and signature of the callback:

submitData(processarResponse(response));
    
asked by anonymous 10.05.2018 / 05:34

2 answers

1

Just use nome_da_funcao() , for example:

function exec( fun ) {
  fun("World") //Passando parâmetros
}

exec( function() {
  console.log("Success")
} )

exec( function(res) {
  console.log('Hello ${res}')
} )

Based on your example:

function submitData(myCallback) {
    $.ajax({
        url: 'https://jsonplaceholder.typicode.com/posts/1',
        success: function(res){
            myCallback(res);
        }
    });
}

submitData(function(res) {
  console.log( "Título do POST: ", res.title )
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Youstilluse apply or call a>, for example:

myCallback.call(null, res)
myCallback.apply(null, [res])

Example:

function submitData(myCallback) {
    $.ajax({
        url: 'https://jsonplaceholder.typicode.com/posts/1',
        success: function(res){
            myCallback.call(null, res)
        }
    });
}

submitData(function(res) {
  console.log( "Título do POST: ", res.title )
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
10.05.2018 / 05:37
1

Just remove the quotation marks that will work:

function submitData(myCallback) {
    $.ajax({
        success: function(res){
            myCallback(res);
        }
    });
}

myCallback must be able to receive the last parameter

    
10.05.2018 / 05:57