[英]Executing a function after an another (asynchronous) function finishes in JavaScript
[英]JavaScript: Continue with function after another function call finishes
小提琴应该用来帮助说明我正在尝试做的事情和正在发生的事情。 子选择项应填充第二个选项值。
不确定最好的询问方法。 我正在创建一个测试脚本以自动填充表单上的输入。
它包括一系列下拉select
框,它们在onChange事件中填充其他select
选项。 尝试自动填充表单时,子选择没有任何选项。
console.clear();
// non-select inputs
$(':input:not([type="hidden"],[type="button"])').each(function(){
$(this).val($(this).attr('name')) // test value is simple input's name
});
// select inputs
var count=0, cutoff=7500;
$('select').each(function(){
var t = $(this);
var c = t.children('option');
while( c.length <= 1 && count < cutoff){
count++;
c = $(this).children('option'); // tried not using the cache'd variable
if (!(count % 10))
console.log(count, c.length, "No Options"); // debugging -- never exists early
setTimeout(function(){},0); // not really doing anything
}
t.val( c.eq(1).val() ); // set value to second option value
t.trigger('change'); // calls the onChange even if it doesnt exist
});
// verify it does have data
console.log($('#sub-select').children('option').length); // does have options
更改事件中有一个AJAX调用。 我可以修改回调,但这只是一个简单的测试脚本,是从控制台运行的。 有任何想法吗?
不太确定您的代码正在尝试做什么
但是回答另一个函数调用完成后如何继续操作的问题:
假设您有一个全部异步的函数列表,则可以嵌套它们以继续
到下一个异步函数... asyncCall(callback1){callback1(callback2){callback2(...)}}
检出https://github.com/caolan/async以获得一些优雅的方法
本示例按顺序调用所有函数,即使它们是异步的。
async.series([
function(callback){
setTimeout(function(){
call_order.push(1);
callback(null, 1);
}, 25);
},
function(callback){
setTimeout(function(){
call_order.push(2);
callback(null, 2);
}, 50);
},
function(callback){
setTimeout(function(){
call_order.push(3);
callback(null, 3,3);
}, 15);
}
1)使用同步AJAX请求http://api.jquery.com/jQuery.ajax/
var html = $.ajax({
url: "some.php",
async: false
}).responseText;
2)不要使用.each,而要使用.eq(index)并按顺序调用它。
function FakeEach(idx) {
if(idx >= 7500) return;
var $obj = $('select').eq(idx);
if($obj.length == 0) return;
...
$obj.trigger('change');
window.setTimeout(function() { FakeEach(idx++); }, 0);
}
您的问题是您正在函数中启动AJAX请求,并期望响应在函数结束之前到达。 只要您使用异步请求,就永远不会发生这种情况。 您必须先退出函数,然后才能运行处理响应的代码。 Javascript是单线程的,因此只要您的函数正在运行,其他任何代码都无法运行。
该问题的解决方案是将使用数据的代码放入响应到达后调用的成功回调函数中。 即使您通常在进行AJAX调用的函数中编写该函数,但它是一个单独的函数,稍后会运行。
如果确实需要与AJAX调用相同功能的数据,则需要发出同步请求。 但是,这是用户体验的杀手,因为整个浏览器在等待响应时会冻结。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.