gpt4 book ai didi

javascript - 如何同步 ajax 和非 ajax 代码路径

转载 作者:行者123 更新时间:2023-11-30 12:36:54 25 4
gpt4 key购买 nike

所以我有这个篮子功能,您可以在其中输入作者姓名,它会列出可用的书籍。你选择你想要的,然后你可以点击选择另一个作者。当您这样做时,您会得到一个大致如下所示的列表:

Stephen King                                 
The Stand [remove]
The Talisman [remove]
Pet Sematary [remove]

Terry Pratchett
Mort [remove]
Guards Guards [remove]

在上面的示例中,Stephen King 的书籍已存储在 Session 中,而 Terry Pratchett 的书籍没有。如果我单击 Pratchett 书中的删除按钮,一些 jquery 将只隐藏那些。如果我删除一本 Stephen King 的书,会触发一个 ajax 请求,在 jquery 隐藏它之前将它从 Session 中删除。

所以我的 javascript 看起来像这样:

$('.book-remove').click(removeBook);

function deleteFromBasket(bookId) {
var ajaxArgs = { BookId : bookId };
return $.ajax({
// blah blah, no problems here
success: function(e) {
hideRow();
}
});
}

function hideRow(bookId) {
$('.book-id-' + bookId).hide();
}

function removeBook(e) {
e.preventDefault();

if ($(this).hasClass('needs-ajax-call') {
var promise = deleteFromBasket($(this).prop("id").replace("book-id-", ""));

// this is the problem. how do I wait here for the ajax to complete?
}
else
hideRow();

// if i put promise.done(hideRow) up there, it still runs this too soon.
doMoreStuff();
}

最佳答案

您可以构建所有代码(包括使用和不使用 ajax 的代码路径)以使用 promises。不需要执行 ajax 调用的代码可以从一个已经解析的 promise 开始,并且两个代码路径将执行相同的序列(一个执行起来会更快,因为它不必等待 ajax 调用), 但两者都将以相同的顺序执行:

在 ajax 调用之后你想要完成的任何事情都必须简单地移动到 promise.then() 处理程序中:

function removeBook(e) {
e.preventDefault();
var promise;

if ($(this).hasClass('needs-ajax-call') {
promise = deleteFromBasket($(this).prop("id").replace("book-id-", ""));
} else {
// get an already resolved promise since no ajax call is required
promise = $.Deferred().resolve();
}
// you can return this promise if you want the calling code
// to be able to know when you're done with everything
return promise.then(function() {
hideRow(bookId); // assumes you've calculated a bookId somewhere
doOtherStuff();
});
}

这样做的好处是您的大部分代码都在一个代码路径中,而不是两个单独的代码路径中,它解决了您的问题,因为 .then() 处理程序中的所有代码都不会执行直到 ajax 调用完成。

关于javascript - 如何同步 ajax 和非 ajax 代码路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25790463/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com