Skip to content Skip to sidebar Skip to footer

Javascript Array Debugging, A Mater Of Scope

How do I return the response from an asynchronous call? Did not helped me and will probably confuse a lot on googlers because its state what is working as not working. witch i

Solution 1:

var data = validateInput2(field_id, data_type, value).then(function (response) {
        console.log("Succès !", response);
        data = response;
        if (data[0] == 'true') {
            $(container[1]).addClass("pass_f");
            $(container[1]).html(data[2]);
            $(container[0]).html(data[1]);
        }
        else {
            $(container[1]).removeClass("pass_f");
            $(container[1]).addClass("err_f");
            $(container[1]).html(data[2]);
            $(container[0]).html(data[1]);
        }
    }, function (error) {
        console.error("Échec !", error);
    });
    alert('DATA : '+data);

it's because you are working with data, and data in that moment is promise, so do it like this

Solution 2:

I have unwound your callback function for clarity, for you to spot the error:

var success_func = function (response) {
    console.log("Succès !", response);
    data = response;
    alert('R : '+data);
};
var error_func = function (error) {
    console.error("Échec !", error);
};
var data = validateInput2(field_id, data_type, value).then(success_func, error_func);
alert('DATA : '+data);
if (data[0] == 'true') {
    // ...
} else {
    // ...
}

success_func is called some time in the future, when your ajax call has completed. So when validateInput2 returns, it's likely that success_func is not yet even called. then returns a Promise object, not the data from server you would expect.

Right way to handle the situation is to put all your data handling inside success_func:

validateInput2(field_id, data_type, value).then(function (response) {
    console.log("Succès !", response);
    data = response;
    if (data[0] == 'true') {
        $(container[1]).addClass("pass_f");
        $(container[1]).html(data[2]);
        $(container[0]).html(data[1]);
    }
    else {
        $(container[1]).removeClass("pass_f");
        $(container[1]).addClass("err_f");
        $(container[1]).html(data[2]);
        $(container[0]).html(data[1]);
    }
}, function (error) {
    console.error("Échec !", error);
});

Post a Comment for "Javascript Array Debugging, A Mater Of Scope"