Return from a nested function after an AJAX call

I have a situation where I have to check something through AJAX, and then return the result. Or simplified:

function isValid() { $.ajax(URL, data, function(response) { isValid = response; }); return isValid; } 

but still can't do it.

I can get an answer, but I can’t do isValid return AFTER I get the answer. For example, the solution I see everywhere:

 function isValid() { function checkOnServer(callback) { $.ajax(URL, data, function(response) { callback(response); }); } checkOnServer(function(response) { alert(response); }); } 

I met this all on top of Stackoverflow, BUT the problem is:

  • I do not want to warn about this.
  • I want to RETURN it from isValid ().

=============================

EDIT: I forgot to mention that if you / we / just try to “return” with “checkOnServer”, it will simply return it to the AJAX callback. But the goal here is to make "isValid" return the result ... :)

0
source share
1 answer

your code is reasonable, but you use the callback function in isValid (), so it doesn’t warn you !, I also slightly modified your ajax function below

 function isValid() { checkOnServer(function(response) { alert(response); }); } function checkOnServer(callback) { $.ajax({ url : URL, data : data, success : function(response) { callback(response); } }); } 

Edit

A variable cannot return from an asynchronous method? If we call a function with ajax, the call function is started first immediately before the ajax response, so it returns undefined only using the method described above.

There is two method I've know to return from asynchronous function

Call after ajax function execution

  function isValid() { var data; checkOnServer(function(response) { data = response; }); return data; } function checkOnServer(callback) { $.ajax({ url : URL, data : data, async : false }).done(function(response){ callback(response); }); } console.log(isValid()); 

Assign a variable using responseText

  function isValid() { var data = checkOnServer(); return data; } function checkOnServer() { var data = $.ajax({ url : URL, data : data, async : false //must set async to false }); return data.responseText; } console.log(isValid()); 
0
source

Source: https://habr.com/ru/post/1344902/


All Articles