gpt4 book ai didi

javascript - 添加 .done() 回调到自定义函数

转载 作者:行者123 更新时间:2023-11-29 16:13:09 24 4
gpt4 key购买 nike

我将这些函数包含在一个小类中:

var Ajax = {
// Send new entry data to database
endNewEntry: function (json) {
$.post("/controllers/insertEntry.ajax.php", {"json": json});
},
loadView: function (view, target, extra) {
var input = $.extend({}, {"view": "../" + view}, extra) || {"view": "../" + view};

$.get("/controllers/loadView.ajax.php", input, function (data) {
$(target).replaceWith(data);
});
}
};

如您所见,这两个函数都使用 jQuery $.ajax 向我的服务器执行请求并用响应替换我的部分文档。

现在我想为这些函数添加一个特性,让我在发布请求完成时调用另一个函数(回调)。

我想要这样的语法:

Ajax.loadView(view, target, extra).done( function() { something; });

相反,我知道的唯一方法是向定义回调函数的 loadView 添加另一个参数,但我想要 .done()功能。

我该怎么办?

最佳答案

done 是 promise API 的一部分。

Promises 是对流程控制的抽象,让您可以以“更同步”的方式编写异步代码。

一个 promise 对象有一个 .then 方法,允许您将操作链接到它,并且保证每个操作仅在前一个操作完成时终止。

myAjax().then(function(result){
// do something with result, myAjax done here
return otherAjax();
}).then(function(otherResult){
// otherAjax done here, this only gets called after the above code handling myAjax is done
});

Promise 实现,至少其中一些,包括一个类似于 .then.done 方法,不同之处在于它将错误记录到控制台而不是允许您在 promise 链中处理它们( promise 可以做的另一件很棒的事情)。

您可以简单地返回您的情况下的 promise :

var Ajax = {
// Send new entry data to database
endNewEntry: function (json) {
return $.post("/controllers/insertEntry.ajax.php", {"json": json});
},
loadView: function (view, target, extra) {
var input = $.extend({}, {"view": "../" + view}, extra) || {"view": "../" + view};

return $.get("/controllers/loadView.ajax.php", input, function (data) {
$(target).replaceWith(data);
});
}
};

哪个会让你做:

Ajax.loadView().done(function(data){
//do something with the result, in variable data here.
});

您当然可以像上面说明的那样将事物链接到它,以便执行多个异步操作。 jQuery 还提供了 $.when 用于等待多个 promise 。

值得一提的是,现在有更好、更快、更强大的 promise 实现。

关于javascript - 添加 .done() 回调到自定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22454245/

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