如何在jquery中使用承诺?

问题描述 投票:0回答:1

我正在通过多个ajax调用拉入多个div。在第一个ajax调用之前,我想显示一个加载的spinner。一旦所有的divs(这将需要一个未知的时间)加载完毕,我想对它们进行排序。最后,我想删除加载微调层。

我想我需要使用承诺(因为有多个ajax调用),但是我不明白如何实现承诺--谁能告诉我如何写承诺,如果我需要在我的函数中添加相关代码,请问该添加什么?

非常感谢您。

这是我的代码。

$(document.body).on('click', "#refresh_view", function(){

    start_spinner();
    load_all_divs(list_of_ids_to_loop_over);

    // once the above is complete
    re_order_divs();

    // once the above is complete
    end_spinner();

});


load_all_divs(list_of_ids_to_loop_over) {

    $.each(list_of_application_ids.split(','), function(index){
        do_ajax_call_for_this_one_item(this)
    });
};


jquery jquery-deferred
1个回答
1
投票

如果你是用jQuery加载divs的 $.ajax (或 $.get等),你可以使用jQuery的 $.when因为那些已经返回jQuery jqXHR 对象,这是承诺式的。

$.when(
    $.ajax(/*...*/),
    $.ajax(/*...*/),
    $.ajax(/*...*/)
)
.done(() => {
    // All done
})
.fail(error => {
    // Something went wrong
});

如果你使用的是最新版本的jQuery,你也可以使用标准的 Promise.all,因为 jqXHR 在现代版本的jQuery中,对象是 可以. Promise.all 接受一个数组。

Promise.all([
    $.ajax(/*...*/),
    $.ajax(/*...*/),
    $.ajax(/*...*/)
])
.then(() => {
    // All done
})
catch(error => {
    // Something went wrong
});
© www.soinside.com 2019 - 2024. All rights reserved.