How to create functions with callback?

Asked

Viewed 1,340 times

4

Can anyone tell me how to create functions with callback? I created this function but it’s not working.

        function PostsCategoriasListar(table, select, callback) {
        if (table) {
            $.ajax({
                url: controller_dashboard,
                type: 'POST',
                dataType: 'json',
                data: {acao: 'PostsCategoriasListar', Listar: 'table'},
                success: function(response) {
                    if (response.status === 'LogOff') {
                        window.setTimeout(function() {
                            window.location.reload();
                        }, 10000);
                    }
                    $element.find('table tbody').html(response.table);
                    ExecuteDataTable(0, maximo, 1);
                },
                error: function(error) {
                    console.log(error);
                }
            });
        }
        if (select) {
            $.ajax({
                url: controller_dashboard,
                type: 'POST',
                dataType: 'json',
                data: {acao: 'PostsCategoriasListar', Listar: 'select'},
                success: function(response) {
                    if (response.status === 'LogOff') {
                        window.setTimeout(function() {
                            window.location.reload();
                        }, 10000);
                    }
                    $element.find('form select').html(response.select);
                },
                error: function(error) {
                    console.log(error);
                }
            });
        }
        //EU QUERO QUE O CALLBACK SO EXECULTE DEPOIS QUE TODO CODIGO QUE ESTIVER NOS IF'S ACIMA TENHAN TERMINADO, ELE SEMPRE EXECULTA ANTES ONDE ESTOU ERRANDO?
        if (typeof callback === 'function')
            callback();
    }

PS: I did not put the ajax requests because it would make it too big and they are working only I need them to execute first and after they finish the callback is executed

  • Place the call to callback() within itself success. Since Ajax calls are asynchronous (by default), if you put it off it will be called before Ajax even starts. There is no problem in referring to a function variable within another more internal function (i.e. closure).

1 answer

4


You need to call the callback when receiving the response to the ajax request. Note that in your logic it may be that two ajax requests are made (if (table) and if (select)). The code below assumes this is not the case, then I took the if select in the first if Else.

function PostsCategoriasListar(table, select, callback) {
    if (table) {
        $.ajax({
            url: controller_dashboard,
            type: 'POST',
            dataType: 'json',
            data: {acao: 'PostsCategoriasListar', Listar: 'table'},
            success: function(response) {
                if (response.status === 'LogOff') {
                    window.setTimeout(function() {
                        window.location.reload();
                    }, 10000);
                } else {
                    $element.find('table tbody').html(response.table);
                    ExecuteDataTable(0, maximo, 1);
                    callback();
                }
            },
            error: function(error) {
                console.log(error);
                callback(error);
            }
        });
    } else if (select) {
        $.ajax({
            url: controller_dashboard,
            type: 'POST',
            dataType: 'json',
            data: {acao: 'PostsCategoriasListar', Listar: 'select'},
            success: function(response) {
                if (response.status === 'LogOff') {
                    window.setTimeout(function() {
                        window.location.reload();
                    }, 10000);
                } else {
                    $element.find('form select').html(response.select);
                    callback();
                }
            },
            error: function(error) {
                console.log(error);
                callback(error);
            }
        });
    } else {
        callback('Ou table ou select precisam ter um valor');
    }
}

One more suggestion: call the callback even in the case of the error (passing the error as parameter). In this case, who called the function PostsCategoriasListar may know if an error has occurred or not:

PostsCategoriasListar(function(error) {
    if (!error) {
         // executado com sucesso
    } else {
        // houve um erro na chamada
    }
});
  • Thank you very much was not exactly what I needed because in this function I sometimes need to execute the Ajax requests of the 2 "if" but your answer gave me a light of how to do, I’ve done it here and it worked very well. thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.