I have two functions
First function:
sendRequest: function () {
jQuery.ajax({
type: 'POST',
url: xtremeSearchUrl,
dataType: 'json',
async: true,
data: JSON.stringify(data),
success: function (data) {
data = this.searchBP();
if (data == false) {
}else{
}
},error{
}});
}
Second function:
searchBP: function () {
var $url = "/bP";
var $data = {url: window.location.pathname};
jQuery.ajax({
type: 'POST',
url: $url,
data: $data,
success: function (result) {
console.log(result);
return true;
},
error: function (xhr, status, error) {
console.log(xhr);
console.log(status);
console.log(error);
return false;
}
});
}
I understand that ajax is executed asynchronously and by setting async to false it pauses the whole page, what I need to do is that when I call the searchBP() function nothing else is executed until it returns true or false and handle according to that response another block of code in sendRequest
Your function
searchBP
returns nothing. When you dodata = this.searchBP();
data, it does not have the value with which it is resolved,searchBP
it is simplyundefined
.The correct way would be to
searchBP
return a promise (jQuery.ajax returns promises)and then you could use it in
sendRequest
likeHowever, you should get used to using
then
andcatch
when executingjQuery.ajax
instead of usingsuccess
anderror
which work as callbacks and do not adhere to the standard of using promises.note that
catch
it is used since jQuery 3. In jQuery 2.x it is usedfail
.You already answered yourself. Do your first non-async function with
async: false
, it won't do the second one until success.