Sequential function calls in javascript

JavaScript函数调用顺序

问题 (Question)

I want function A to finish execution and only after that function B should start executing. When I call function A and then function B, it seems both are executing simultaneously. And after function B completes, I want to call a third function update_dropdown().

My code looks like this:

function A {
    for (var i = 0; i < 5; i++) {
        var promise = $.get(url);
        $.when(promise).then(function () {
            $.post(url);
        });
    }
}
function B {
    $.get(url);
    var promise = $.post(url);
    $.when(promise0).then(function () {
        update_dropdown();
    });
}

Please can you tell me how I can make these 3 function calls happen sequentially.

我想要的功能执行完之后,乙方应开始执行功能。当我调用函数然后函数B,似乎同时执行。和功能B完成后,我想打电话给三分之一个功能update_dropdown()。

我的代码看起来像这样:

function A {
    for (var i = 0; i < 5; i++) {
        var promise = $.get(url);
        $.when(promise).then(function () {
            $.post(url);
        });
    }
}
function B {
    $.get(url);
    var promise = $.post(url);
    $.when(promise0).then(function () {
        update_dropdown();
    });
}

请你能告诉我怎样才能使这3个函数调用发生顺序。

最佳答案 (Best Answer)

Something like this should work

function A {
    var xhr = [];

    for (var i = 0; i < 5; i++) {
        xhr.push( $.get(url) );
    }

    $.when.apply(undefined, xhr).then(B);
}

function B {

    $.when( $.post(url) ).then(update_dropdown);

}

Note the use of an array to keep the promises in, then using $.when with apply() to fire a callback when all the ajax requests in the loop has finished.

注意数组保持承诺,在使用上,然后使用

function A {
    var xhr = [];

    for (var i = 0; i < 5; i++) {
        xhr.push( $.get(url) );
    }

    $.when.apply(undefined, xhr).then(B);
}

function B {

    $.when( $.post(url) ).then(update_dropdown);

}

$.when火回调时回路中所有的AJAX请求已完成。apply()火回调时回路中所有的AJAX请求已完成。

答案 (Answer) 2

Javascript without extra work is single threaded. that means functions are not able to be executed simultaneously. but the problem is that the $.get() and $.post() calls are asynchronous. that means they are executed whenever the requested data arrives your client. (first come first serve)

an solution would be to execute function B after all the results ob A arrived, or to hold back all results and handle all data at once then run update_dropdown().

没有额外的工作,JavaScript是单线程的。这意味着功能不能同时执行。但问题是,美元。get()美元post()调用是异步的。这意味着它们时执行所请求的数据到你的客户。先来后到。

一种解决方案是执行功能B毕竟结果一到达,或阻止所有的结果和处理所有数据,马上就跑update_dropdown()

本文翻译自StackoverFlow,英语好的童鞋可直接参考原文:http://stackoverflow.com/questions/23451163