Jquery 在不更改函数的情况下异步调用函数
我创建了一个例子来告诉你我的问题是什么。我会发布代码,然后解释 我的JS:Jquery 在不更改函数的情况下异步调用函数,jquery,ajax,asynchronous,Jquery,Ajax,Asynchronous,我创建了一个例子来告诉你我的问题是什么。我会发布代码,然后解释 我的JS: $('#mybtn').on('click', function(){ //$(fn1).promise().done(fn2); $.Deferred(fn1).then(fn2); }); function fn1(){ console.log("1"); $.ajax({ url: 'ajax.php', type: 'POST',
$('#mybtn').on('click', function(){
//$(fn1).promise().done(fn2);
$.Deferred(fn1).then(fn2);
});
function fn1(){
console.log("1");
$.ajax({
url: 'ajax.php',
type: 'POST',
data: {
func: "1"
},
success: function(data){
console.log(data);
}
});
}
function fn2(){
console.log("2");
$.ajax({
url: 'ajax.php',
type: 'POST',
data: {
func: "2"
},
success: function(data){
console.log(data);
}
});
}
我的PHP:
<?php
$request = $_POST['func'];
switch ($request) {
case '1':
fn1();
break;
case '2':
fn2();
break;
}
function fn1(){
print "1";
sleep(4);
}
function fn2(){
print "2";
sleep(2);
}
?>
谢谢。否。由于函数无法让调用者知道何时完成,因此您不能等待它们完成。您需要以某种方式更改函数
严格地说,它可以通过monkeypatching来完成,但这是一种可怕的方式。不能将回调传递给每个函数吗?@tymeJV我想我不明白,你的确切意思是什么?例如
函数fn1(回调)
然后在success@tymeJV如何向每个函数添加回调?'-'我猜它不会等待它们内部的函数结束…@tymeJV-hmmm思考。。。
toWait.someWayToWait().then(anotherFunctionToWait());
function toWait(){
//whatever code or functions in here.
fn1();
fn2();
fnX();
}
function anotherFunctionToWait(){
//whatever code or functions in here.
}