如何等待异步在jquery中完成

时间:2015-09-23 02:57:02

标签: javascript jquery json asynchronous

有无数类似的线索,但没有规范的似乎回答了我的问题。还有许多似乎涉及真正复杂的解决方案似乎应该有一个简单的解决方案。

无论如何,我的基本问题是如何让它按顺序运行:

console.log('step 1');

$.getJSON('foo.json', function(data) {
    console.log('step 2');
});

console.log('step 3');

这导致控制台输出:

step 1
step 3
step 2

这样的事情似乎是合理的,这会使文件加载之前停止功能,但它不起作用。

$.getJSON('foo.json', function(data) {
    console.log('step 2');
}).done();

其他线程建议您可以创建$.Deferred()对象,这些对象可以链接then().then()之类的调用,然后以某种方式完成它们,但这没有用,因为我实际上有这种时尚的功能:

function first() {
    $.getJSON('foo.json', function(data) {
        console.log('step 1');
    });
}

function second() {
    $.getJSON('foo.json', function(data) {
        console.log('step 2');
    });
}

// Even if I defer them to wait until the next function finishes,
// the `getJSON` calls won't have finished and I'm back where I started.
function call_them() {
    first();
    second();
    console.log('step 3');
}

其他地方有人建议我可以尝试使用$.when(),这似乎是一个很大的麻烦,即使它会起作用,但当我尝试时却没有。我试过这样的事情:

function do_first() {
    $.when(first())
     .done(function() { console.log('first is finished'); });
}

function first() {
    return $.getJSON('foo.json', function(data) {
        console.log('step 1');
    });
}

function do_second() {
    $.when(second())
     .done(function() { console.log('second is finished'); });
}

function second() {
    $.getJSON('foo.json', function(data) {
        console.log('step 2');
    });
}

function call_them() {
    do_first();
    do_second();
    console.log('step 3');
}

无论如何,这似乎应该很容易,但我不知道你应该如何做这项工作。此外,它在async被禁用时效果很好,但对于使用此功能的网站来说这是站不住脚的。

1 个答案:

答案 0 :(得分:0)

对于第一个,它可以像这样,按顺序工作

console.log('step 1');

$.getJSON('foo.json', function(data) {
    console.log('step 2');
    step3();
});

function step3()
{
   console.log('step 3');
}

用于下一个建议

function first(callback) 
{
    $.getJSON('foo.json', function(data) {
        console.log('step 1');
        callback();
    });
}

function second(callback) 
{
    $.getJSON('foo.json', function(data) {
        console.log('step 2');
        callback();
    });
}

function call_them() 
{
    first(function()
    {
         second(function()
         {
            console.log('step 3');
         });
    });
}

并且对于最后一个建议,你不必使用它