I need to return the parsing result of the XHR request to the Class scope

Asked

Viewed 33 times

1

class AjaxHelper {

    constructor( service, requestType, bol ) {

        this._uri = service;
        this._requestType = requestType;
        this._async = bol;
        this._domain = 'https://private-4e803-salarycalculatorapi.apiary-mock.com';
        this._url = this._domain + '' + this._uri;

        let xhr = new XMLHttpRequest();
        xhr.addEventListener("load", transferComplete, false);
        xhr.open(this._requestType, this._url, this._async)
        xhr.send();                  

        function transferComplete(event) {
            var data = JSON.parse(event.target.responseText);
            return data;
        }

        console.log(data);

    }

    get url() {
        return this._url;
    }

}

I need to return the JSON parsing result of the XHR request to the Class scope, but I cannot understand how the functions passed on the request object work. VAR DATA ONLY EXISTS WITHIN ITS SCOPE.

    <script src="app/helpers/AjaxHelper.js"></script>
    <script>

        var myresource = new AjaxHelper('/inss','GET', true);
        myresource.data;

    </script>

1 answer

0


The problem is that the ajax call is asynchronous, so there is no way of knowing when it will actually run and consequently return the value. And in the line where I would normally try to get the value, following the new AjaxHelper(...);, the value is not yet available.

Instead you can pass one callback to the constructor of your class, with the code you want to execute in the reply. This callback has to be called on transferComplete:

class AjaxHelper {

    constructor( service, requestType, bol, callback /*callback agora aqui*/ ) {

        this._uri = service;
        this._requestType = requestType;
        this._async = bol;
        this._domain = 'https://private-4e803-salarycalculatorapi.apiary-mock.com';
        this._url = this._domain + '' + this._uri;
        this.callback = callback; //guarda o callback na classe

        let xhr = new XMLHttpRequest();
        xhr.addEventListener("load", transferComplete, false);
        xhr.open(this._requestType, this._url, this._async)
        xhr.send();                  

        function transferComplete(event) {
            var data = JSON.parse(event.target.responseText);
            callback(data); //callback chamado aqui com os dados da resposta
        }

        console.log(data);

    }

    get url() {
        return this._url;
    }

}

And now you call it:

<script>
    //callback recebe os dados da resposta como parâmetro 
    new AjaxHelper('/inss','GET', true, (dados) => { 
        //aqui usa os dados que são a resposta do ajax
        console.log(dados);
    });

</script>

Browser other questions tagged

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