Return value with XMLHttpRequest

0
     dataPacket: function(type){
        aTurn.packet = new XMLHttpRequest();
        aTurn.packet.open('GET', 'teste.php', true);
        aTurn.packet.send();

        aTurn.packet.onreadystatechange = function(){
            if(aTurn.packet.readyState == 4 && aTurn.packet.status == 200){
                data = JSON.parse(aTurn.packet.response);
                return data.current;
            }
        }
    },

I'm using this function to get values from a json file. However, when triggered I would like to return the value date, just like I did in the example, but returns undefined, what can I do?

It would be possible to use the dataPacket () type parameter to set the final value, for example: dataPacket ('test') would return the data.test.

    
asked by anonymous 14.04.2018 / 00:44

1 answer

1

You can not return a value from an asynchronous function, you can use a callback function or a Promise.

Ex callback:

dataPacket: function(type, callback){
        aTurn.packet = new XMLHttpRequest();
        aTurn.packet.open('GET', 'teste.php', true);

        aTurn.packet.onreadystatechange = function(){
            if(aTurn.packet.readyState == 4 && aTurn.packet.status == 200){
                data = JSON.parse(aTurn.packet.response);

                // Chamada do callback
                if( typeof callback == 'function' ) {
                    callback(data);

                    // Ou caso, queira pegar o valor de type
                    callback(data[type]) 
                }
            }
        }

        aTurn.packet.send();
    },

Call

dataPacket('teste', function(resultado){
   console.log(resultado);
})
    
14.04.2018 / 01:06