Reputation: 18745
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):
Do you have any ideas?
Upvotes: 2
Views: 134
Reputation: 1074989
You're really close. A couple of things:
You forgot to return the promise out of evalXpath
.
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
.
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