I am looking for something like this(我正在寻找这样的东西)
function someFunc() {
callAjaxfunc(); //may have multiple ajax calls in this function
someWait(); // some code which waits until async calls complete
console.log('Pass2');
}
function callAjaxfunc() {
//All ajax calls called here
console.log('Pass1');
}
What I have tried?(我试过了什么?)
1 Jquery.when()(1 Jquery.when())
tried using it..it works fine.(尝试使用它..工作正常。) But not the way I want.(但不是我想要的方式。) $.when
will wait but the code next to $.when()
runs with out waiting.($.when
等待,但$.when()
旁边的代码运行时没有等待。) The code inside do callback
only runs after ajax calls(里面的代码do callback
只在ajax调用之后运行)
2. setTimeOut() with a global flag(2. setTimeOut()带有全局标志)
I was so confident this will work.(我非常有信心这会奏效。) I tried like following.(我试过跟随。)
GlobalFlag = false;
function someFunc()
callAjaxfunc(); //may have multiple ajax calls in this function
setTimeOut(waitFunc, 100); // some which waits until async calls complete
console.log('Pass2');
}
function callAjaxfunc() {
//All ajax calls called here
onAjaxSuccess: function() {
GlobalFlag = true;
};
console.log('Pass1');
}
function waitFunc() {
if (!GlobalFlag) {
setTimeOut(waitFunc, 100);
}
}?
Still not able to get wanted result.(仍然无法得到想要的结果。) Am I doing something wrong here?(我在这里做错了吗?) This is not the way?(这不是办法吗?)
Result I wanted should come like this(我想要的结果应该是这样的)
Pass1
Pass2
Not able to make any fiddle as it needs AJAX calls(因为需要AJAX调用所以无法做任何小提琴)
EDIT : As many were suggesting callbacks..i know about them..but still the code next to somewait()
will get executed...I want browser to completely stop executing code next to somewait()
until the ajax call..Also it may be a bad practice but worth to know and try if possible...(编辑 :正如许多人建议回调..我知道他们..但仍然somewait()
旁边的代码将被执行...我希望浏览器完全停止执行somewait()
旁边的代码,直到ajax调用..还要这可能是一个不好的做法但值得知道并尽可能尝试......)
ask by thecodejack translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…