Milano
Milano

Reputation: 18745

Function doesn't return anything (async?)

I'm trying to add XPATH evaluation into my form. When user fills XPATH, it's evaluated on a server using AJAX and then return true or false.

The problem is that this function seems to return undefined allways. I suppose it's because of asynchronious behaviour of JS so I used $.when but it didn't helped.

function evalXpath(xpath) {
    var test = $.post('/api/test-xpath/', {'xpath': xpath});
    test.done(function (data) {
        console.log('BEFORE RETURN '+Boolean(data['success']));
        return Boolean(data['success']);
    })
}

$(document).ready(function () {
    $('#id_xpath').on('change', function () {
        var xpath = $("#id_xpath").val();
        $.when(evalXpath(xpath)).done(function (evaluated) {
            console.log('RETURNED '+evaluated);
            $('#xpath-valid').text(evaluated ? 'VALID' : 'INVALID');
        });


    });

});

The console output (as you can see, it's still asynchronious):

enter image description here

Do you have any ideas?

Upvotes: 2

Views: 134

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074989

You're really close. A couple of things:

  1. You forgot to return the promise out of evalXpath.

  2. To get proper promise value chaining (e.g., in order for your value from the callback inside evalXpath to then become the resolution value of the promise it returns), use then, not done.

  3. Then when using evalXpath, there's no need for $.when.

So:

function evalXpath(xpath) {
    var test = $.post('/api/test-xpath/', {'xpath': xpath});
    return test.then(function (data) {
//  ^^^^^^      ^^^^
        console.log('BEFORE RETURN '+Boolean(data['success']));
        return Boolean(data['success']);
    })
}

// ...
evalXpath(xpath).then(function (evaluated) {
//               ^^^^ (this one could be `done`, but let's be consistent)

Upvotes: 3

Related Questions