Promise Javascript

Asked

Viewed 52 times

0

I have a scenario where I make several Ajax calls to a Webapi and with the return I load controls from an application.

I would like to create a unique method to call the API, which would receive a parameter with the link, for example 'api/List categories/'. In this method I would like to return if error occurred and the list (json) recovered.

I created the following method for calling AJAX:

        const URL_BASE = "http://10.1.1.121/App/";

    function executaChamadaAPI(URL_API) {
        const URL_SERVICO = URL_BASE + URL_API
        let resultado = {
            erro: "NOK",
            lista: {}
        };
        $.get(URL_SERVICO, function (data) {
            data = $.parseJSON(data);
        })
        .done(function (data) {
               resultado.erro = "OK";
                resultado.lista = $.parseJSON(data);;
        })
       .fail(function () {
                resultado.erro = "NOK";
        })
        .always(function () {
                return resultado;
        });
    }

I would like to create a function for each control I have to load: categories, users and etc. by calling the generic method for running Ajaxecutachamadaapi, passing the path, something like that:

        function carregaCategorias{
        var res = executaChamadaAPI('api/ListaCategorias/');

        //Aguardar a execução e retorno do método executaChamadaAPI para posteriormente usar o retorno

        if (res.erro == 'OK'){
            res.lista.forEach(function (o, index) {
                let idCategoria = o.id;
                var html = '<p>' + idCategoria + '</p>';
                $("#result").prepend(html);
            });
        }
        else{
            alert('erro ao executar executaChamadaAPI' );
        }
    }

I did it this way, but I don’t know if it’s the best:

        const URL_BASE = "http://172.16.106.87/App/";


    function carregaCategorias(res) {
        if (res.erro.toUpperCase() == "OK") {
            res.lista.forEach(function (o, index) {
                let srcImg = URL_BASE + o.PathImagem;
                let idCategoria = o.id;
                var html = '<p>' + idCategoria + '</p>';

                console.log(html);

                $("#result").prepend(html);

            });
        }
        else
            alert('errou rude');
    }

    function executaChamadaAPI(funcRetorno, URL_API) {
        const URL_SERVICO = URL_BASE + URL_API
        console.log('Entrou executaChamadaAPI ' + URL_SERVICO);

        let resultado = {
            erro: "NOK",
            lista: {}
        };

        $.get(URL_SERVICO, function (data) {
            data = $.parseJSON(data);
        })
            .done(function (data) {
                //console.log(data);
                resultado.erro = "OK";
                resultado.lista = $.parseJSON(data);;
                console.log("Success executaChamadaAPI  " + resultado.lista.length);

            })
            .fail(function () {
                console.log("error executaChamadaAPI");
                resultado.erro = "NOK";
            })
            .always(function () {
                console.log("Complete executaChamadaAPI ");

               funcRetorno(resultado); //chama uma função de acordo com parâmetro passado
                return resultado;
            });
    }

    executaChamadaAPI(carregaCategorias,'api/ListaCategorias/')

Or perhaps it would be better if each function called and handled the AJAX request?

  • 1

    Friend, from what I’ve seen, the best would be each time you call the request function to treat it

1 answer

1


Good you can take the treatments from the AJAX function and return only the promise:

function executaChamadaAPI(URL_API) {
    const URL_SERVICO = URL_BASE + URL_API
    let resultado = {
        erro: "NOK",
        lista: {}
    };
    return $.get(URL_SERVICO, function (data) {
        data = $.parseJSON(data);
    });
}

Then you call the function normally and do the same treatment you had done before

executaChamadaAPI()
.done(function (data) {
           resultado.erro = "OK";
            resultado.lista = $.parseJSON(data);;
    })
   .fail(function () {
            resultado.erro = "NOK";
    })
    .always(function () {
            return resultado;
    });

Browser other questions tagged

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