我在找这样的东西

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()

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. The code inside do callback only runs after ajax calls

2. setTimeOut() with a global flag

我很有信心这会奏效.我试着跟着.

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?

我想要的结果应该是这样的

Pass1
Pass2

由于需要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...

推荐答案

使用回调.基于您的示例代码,类似的东西应该可以工作.

function someFunc() {

callAjaxfunc(function() {
    console.log('Pass2');
});

}

function callAjaxfunc(callback) {
    //All ajax calls called here
    onAjaxSuccess: function() {
        callback();
    };
    console.log('Pass1');    
}

这将立即打印Pass1(假设ajax请求至少需要几微秒),然后在执行onAjaxSuccess时打印Pass2.

Jquery相关问答推荐

在添加_renderMenu方法时,是什么原因导致jQuery UI AutoComplete抛出TypeError?

Sheets从多张sheet中导入range匹配数据

jQuery .val() 和 .attr('value') 有什么区别?

为什么我的 toFixed() 函数不起作用?

元素上的 jQuery Change 事件 - 有什么方法可以保留以前的值?

如何使用 AJAX 和 jQuery 发布 django 表单

纯css关闭按钮

如何使用jquery取消绑定所有事件

jQuery 库中使用的设计模式

jQuery $.browser 是否已弃用?

Ajax 更新后在 jQuery 中重新绑定事件(更新面板)

当ID包含方括号时按ID查找DOM元素?

Angular.js 在多个元素中重复

使html文本输入字段随着我输入而增长?

C# String.IsNullOrEmpty Javascript 等效项

jQuery .hasClass() 与 .is()

jQuery attr 与props ?

获取jQuery中下拉列表的值

JS - 从base64代码中获取图片的宽高

在页面加载之间保持变量