从 1.5 版开始,jQuery 提供了使用Defered对象来处理回调和异步调用管理的实用程序。使用这些类型的对象,客户端可以更轻松地添加在完成某些后台工作时调用的回调。这是使用您的代码的示例:
function some_func_validate(some_id) {
var deferred = $.Deferred(),
context = {
id: some_id,
success: false
};
$.ajax({
type: 'GET',
url: '/something/'+some_id+'/check'
})
.done(function(response){
context.success = true;
context.content = response;
deferred.resolveWith(context);
})
.fail(function() {
deferred.rejectWith(context)
});
return deferred.promise();
}
示例用法:
some_func_validate(5).then (
function (context) {
// Handle successful validation.
console.log(context);
},
function (context) {
// Handle failed validation.
console.log(context)
}
);
另一个使用示例:
function logger (context) {
console.log(context);
}
function onSuccessfulValidation (context) {
// Handle successful validation.
// context contains {id, content, success}
}
function onFailedValidation (context) {
// Handle failed validation.
// context contains {id, success}
}
some_func_validate(3).then (
[logger, onSuccessfulValidation],
[logger, onFailedValidation]
);