我如何设计一个API来隐藏AJAX和HTTP请求的异步性质,或者基本上将其延迟以提供流畅的界面.要在Twitter的新Anywhere API中显示示例:
// get @ded's first 20 statuses, filter only the tweets that
// mention photography, and render each into an HTML element
T.User.find('ded').timeline().first(20).filter(filterer).each(function(status) {
$('div#tweets').append('<p>' + status.text + '</p>');
});
function filterer(status) {
return status.text.match(/photography/);
}
Run Code Online (Sandbox Code Playgroud)
vs this(每个调用的异步性质清晰可见)
T.User.find('ded', function(user) {
user.timeline(function(statuses) {
statuses.first(20).filter(filterer).each(function(status) {
$('div#tweets').append('<p>' + status.text + '</p>');
});
});
});
function filterer(status) {
return status.text.match(/photography/);
}
Run Code Online (Sandbox Code Playgroud)
它找到用户,获取他们的推文时间轴,仅过滤前20条推文,应用自定义过滤器,并最终使用回调函数来处理每条推文.
我猜这样设计良好的API应该像查询构建器(想想ORM)一样工作,每个函数调用构建查询(在这种情况下为HTTP URL),直到它遇到循环函数,如每个/ map /等.进行HTTP调用,传入函数成为回调函数.
一个简单的开发途径是使每个AJAX调用同步,但这可能不是最好的解决方案.我有兴趣找出使其异步的方法,并仍然隐藏AJAX的异步性质.