jQuery:等待函数完成继续处理? [英] jQuery: wait for function to complete to continue processing?
问题描述
$(function(){
var r = GetResults();
for(var i = 0; i< r.length; i ++){
//用r
做东西}
});
函数GetResults(){
$ .getJSON(/ controller / method /,null,function(data){
return data;
});
}
由于我正在异步调用方法,脚本继续执行,当遇到for循环时, r
显然还没有值。我的问题是:当我有一个正在进行异步操作的方法,并且我依赖于它在主块中返回的数据时,如何在数据返回之前暂停执行?类似于:
var r = GetResults(param,function(){
});
其中函数是回调函数。我无法将for循环处理移动到JSON请求的回调函数中,因为我在整个页面中多次重用GetResults的功能,除非我想复制代码。有什么想法吗?
将你的用r做块块移到$ .getJSON回调中。在你交付之前你不能用r做东西,你必须使用r的第一个机会就是回调...那么就这样做。
$(function(){
var r = GetResults();
});
函数GetResults(){
$ .getJSON(/ controller / method /,null,function(data){
for(var i = 0; i< data.length; i ++){
//用数据做
}
返回数据;
});
}
Hey all. I have, what appears to be, a trivial problem. I have the following JavaScript:
$(function() {
var r = GetResults();
for(var i = 0; i < r.length; i++) {
// Do stuff with r
}
});
function GetResults() {
$.getJSON("/controller/method/", null, function(data) {
return data;
});
}
Due to the fact that I'm calling a method asynchronously, the script continues executing and when it encounters the for loop, r
obviously isn't going to have a value yet. My question is: when I have a method that is doing an asynchronous operation, and I'm dependent on the data it returns back in the main block, how do I halt execution until the data is returned? Something like:
var r = GetResults(param, function() {
});
where the function is a callback function. I cannot move the for loop processing into the callback function of the JSON request because I am reusing the functionality of GetResults several time throughout the page, unless I want to duplicate the code. Any ideas?
move your "do stuff with r" block into your $.getJSON callback. you can't do stuff with r until it has been delivered, and the first opportunity you'll have to use r is in the callback... so do it then.
$(function() {
var r = GetResults();
});
function GetResults() {
$.getJSON("/controller/method/", null, function(data) {
for(var i = 0; i < data.length; i++) {
// Do stuff with data
}
return data;
});
}
这篇关于jQuery:等待函数完成继续处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!