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

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 pairing result of the XHR request to the scope of the Class, but I can not understand how the functions passed in the request object work. VAR DATA ONLY EXIST WITHIN YOUR SCOPE.

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

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

    </script>
    
asked by anonymous 30.09.2017 / 15:53

1 answer

0

The problem is that the ajax call is asynchronous, so you have no way to know when it will actually execute and therefore return the value. And in the line where you would normally try to get the value, then new AjaxHelper(...); , the value is not yet available.

Instead you can pass a callback to the your code, with the code that you want to execute on the response. This callback has after being called in 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 call it like this:

<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>
    
30.09.2017 / 16:14