我如何设计一个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的异步性质.
我在JavaScript开发了相当长的一段时间,但仍然净牛仔开发商,如的很多事情总是困扰着我的synching JavaScript的回调之一.
我将描述一个普通的场景时,这一问题将得到提升:我有一大堆的操作由一个for循环执行多次,并且每个操作都有一个回调.在for循环之后,我需要执行另一个操作,但是如果完成了for循环的所有回调,则此操作只能成功执行.
代码示例:
Run Code Online (Sandbox Code Playgroud)for ... in ... { myFunc1(callback); // callbacks are executed asynchly } myFunc2(); // can only execute properly if all the myFunc1 callbacks are done
建议的解决方案:
在循环开始时启动一个计数器,保持循环的长度,并且每个回调递减该计数器.当计数器达到0时,执行myFunc2.这实际上是让回调知道它是否是序列中的最后一个回调,如果是,则在完成时调用myFunc2.
问题:
终极问题:
有更好的解决方案吗?