我有一个 JavaScript Bootstrap 模块,我试图保持它非常干净和简单:目前我有这样的代码:
function bootStrapper() {
xmlRepository.getAll().done(function (result) {
autoPolicyForm.show();
});
}
在 xmlRepository 中,我在 getAll() 中使用延迟对象;
function getAll () {
var d = $.Deferred();
$.ajax({
type: "GET",
url: "http://localhost/Autopolicy/dataSource.xml",
dataType: "xml",
success: function (xml) {
d.resolve(xml);
}
});
return d.promise();
}
这段代码运行良好,但我真的很想将 Bootstrap 代码进一步简化为:
function bootStrapper() {
var result = xmlRepository.getAll();
autoPolicyForm.show();
});
}
由于调用的异步性质,我尝试的所有操作都会导致“结果”未定义。
有谁知道如何修改代码,将复杂的部分移到xmlRepository中,从而实现上述目的?
谢谢
最佳答案
在现代 jQuery 中 the ajax function返回一个 promise ,因此您可以将 getAll
简化为:
function getAll () {
return $.ajax({
type: "GET",
url: "http://localhost/Autopolicy/dataSource.xml",
dataType: "xml"
});
}
换句话说,现在可以做到
$.ajax(url).done(function(xml){...});
您也可以将 getAll 更改为
function fetchAll (callback) {
$.ajax({
type: "GET",
url: "http://localhost/Autopolicy/dataSource.xml",
dataType: "xml"
}).done(callback);
}
所以你会做
xmlRepository.fetchAll(function (result) {
autoPolicyForm.show();
});
但是除了将 async 设置为 false 之外,您无法避免传递函数,因为执行是异步的。并且您应该考虑到 JavaScript 应用程序自然是基于事件的,因此 API 的用户可以使用和传递匿名函数(回调)。
关于javascript - 这段 JavaScript Defer 代码可以简化吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13603782/