admin管理员组文章数量:1310498
I am having a really peculiar case. I want to return
some data - data that is downloaded via ajax. So far async & sync modes don't get the data in time to the return
. Is it possible I could either call return
from a child function for the parent function or could a timeOut solve the issue? I can't think of another way of doing this, but the data must be returned.
I am having a really peculiar case. I want to return
some data - data that is downloaded via ajax. So far async & sync modes don't get the data in time to the return
. Is it possible I could either call return
from a child function for the parent function or could a timeOut solve the issue? I can't think of another way of doing this, but the data must be returned.
- return is NOT a function! Though perhaps raising an exception could do what you want? – Ponkadoodle Commented Feb 26, 2010 at 0:33
-
Is there a certain way that an exception could return an array just like
return
? – Kyle Hotchkiss Commented Feb 26, 2010 at 0:56 - Perhaps it would have been appropriate to tell in your function that you are using jQuery? – zneak Commented Feb 26, 2010 at 0:57
- 1 possible duplicate of how to return value to parent function from nested anonymous function – Patsy Issa Commented Aug 18, 2015 at 10:54
3 Answers
Reset to default 3You could provide a callback function:
function parentfunction(callback) {
callback(getAjax());
}
function childfunction() {
parentfunction(function(ajaxData) {
//Do stuff with data
});
}
The answer to your question is no.
In asynchronous requests, the function has to return before the result is available. To work around this, a callback pattern is used - when calling such a function, you don't expect a return, but rather provide it with a callback - a function to be called once the result is available.
Here's a simple example:
var someValue;
fetchValueFrom('http://example./some/url/with/value', function(val) {
someValue = val;
doSomethingElseWith(someValue);
});
Here we create a function and pass it in as a second param to the fetchValueFrom
call. Once the value is available this function will be called, and will set the variable and call another function to continue execution.
Just pass false
as a third parameter to to XMLHttpRequest.open
. It means "run this query synchronously".
See the reference for yourself.
本文标签:
版权声明:本文标题:ajax - Is there a way to call a Return for a parent function from a child function in javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741789436a2397573.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论