Is there a way to call Return on a parent function from a child function in javascript?

I have a very strange case. I want to return some data - data loaded through ajax. While the async and sync modes do not receive data in time to return . Is it possible that I could call return from a child function for the parent function, or could time solve the problem? I cannot think of another way to do this, but the data must be returned.

+4
source share
3 answers

The answer to your question is no.

In asynchronous requests, the function must return before the result is received. To get around this, a callback template is used - when you call such a function, you do not expect a return, but rather provide it with a callback - a function that will be called when the result is available.

Here is a simple example:

 var someValue; fetchValueFrom('http://example.com/some/url/with/value', function(val) { someValue = val; doSomethingElseWith(someValue); }); 

Here we create a function and pass it as the second parameter to call fetchValueFrom . Once the value is available, this function will be called and will set a variable and call another function to continue execution.

+2
source

You can provide a callback function:

 function parentfunction(callback) { callback(getAjax()); } function childfunction() { parentfunction(function(ajaxData) { //Do stuff with data }); } 
+3
source

Just pass false as the third parameter to XMLHttpRequest.open . This means "execute this request synchronously."

See the link for yourself.

-1
source

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


All Articles