-1

I've been watching for a while the questions here in Stack Overflow about returning arrays on JavaScript, but not a single answer works in my code. It always returns 'undefined'.

This is the important part of the code:

function VisualizadorIzquierdo () {
    // some stuff here
    this.dibujar = function () {
        var datos = obtenerDatos(0);
        alert(datos);                         //<--- This always returns 'undefined'
        // other stuff here
    }
    // more stuff here
}

function obtenerDatos(id) {                                                                             
    var xmlhttp = ConstructorXMLHttpRequest();
    if(!xmlhttp) alert('Error: No se pudo crear el objeto XMLHttpRequest');
    else {
        xmlhttp.onreadystatechange = function() {
            if(xmlhttp.readyState == 4)
            {
                alert(xmlhttp.responseText); //<--- This returns '[1,2,3,4]'    
                return xmlhttp.responseText; 
            }
        }
        xmlhttp.open('GET', rutaLector + '?archivo=' + archivos[id], false);
        xmlhttp.send(null);     
    }
}   

I'v tried defining the variable datos as a new Array() and new Object(). Also I'm trying returning an Object (like {"arreglo" : [1,2,3,4]}), defining a new Array() and new Object() within obtenerDatos(id) function, changing between syncronic and asyncronic, etc ...

But every time it returns 'undefined' :c

So, How can I definitely return an Array from a function?

Thanks in advanced! :)

BTC
  • 3,802
  • 5
  • 26
  • 39
AronNeewart
  • 461
  • 6
  • 18
  • 2
    Assuming that the data returned from your _asynchronous_ call is valid, your alert will be executed prior to the code being returned, hence the undefined. – j08691 Oct 16 '13 at 19:30
  • @j08691 if I delete the alerts, it also doesn't work :( – AronNeewart Oct 16 '13 at 19:39

3 Answers3

0

obtenerDatos() don't have a return. The only 'return' in its context is inside another function that is being dynamically declared to the onreadystatechange, but that one doesn't count. Its a delayed event, that will be ran at some other time when the AJAX request is concluded. obtenerDatos() itself isn't returning anything.

What you have to do is set up a callback function that will be called with the AJAX response to process it once the AJAX is done fetching the data.

This other question might explain it better.

Community
  • 1
  • 1
Havenard
  • 27,022
  • 5
  • 36
  • 62
  • But if I set the *asyncronic* param to *false*, the declaration *var datos = obtenerDatos(0);* does move forward? – AronNeewart Oct 16 '13 at 19:37
  • It doesn't change the fact that `obtenerDatos()` is not returning anything. `onreadystatechange` is, but its going nowhere. – Havenard Oct 16 '13 at 19:38
0

the reason why you are getting undefined is because you are calling obtenerDatos() which then calls

xmlhttp.send(null);

xmlhttp.send(null); <-- is an asynchronous call. so you obtenerDatos() function immediately returns after that. and since you don't have a return statement returning anything for obtenerDatos then the variable datos will get nothing or undefined as it is doing right now.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Sucaritas
  • 51
  • 1
  • 4
  • How can I make it to wait until the asynchronous call ends before returning *nothing*? (is that even possible?) – AronNeewart Oct 16 '13 at 19:43
  • straight from the docs. the open function accepts these parameters void open(DOMString method, DOMString url, optional boolean async, optional DOMString? user, optional DOMString? password); the the one that says async? thats where. here is a link to the docs https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest?redirectlocale=en-US&redirectslug=DOM%2FXMLHttpRequest – Sucaritas Oct 18 '13 at 00:17
0

Try in jQuery.

function VisualizadorIzquierdo () {
    // some stuff here
    obtenerDatos(0).done(function (result) {
        //var datos = obtenerDatos(0);
        alert(result);                        
        // other stuff here
    });
    // more stuff here
}


function obtenerDatos(id) {

    return $.ajax({
        url: rutaLector + '?archivo=' + archivos[id],
        type: "GET",
        success: function (result) { },
        error: function () { },
        traditional: true
    });
}
Carlos Novo
  • 139
  • 4
  • 11