Skip to main content
 首页 » 编程设计

javascript之设计一个流畅的 Javascript 接口(interface)来抽象出 AJAX 的异步特性

2025年05月04日123JustinYoung

我将如何设计一个 API 来隐藏 AJAX 和 HTTP 请求的异步性质,或者基本上延迟它以提供流畅的接口(interface)。从 Twitter 的新 Anywhere 中展示一个示例接口(interface):

// 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/); 
} 

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/); 
} 

它找到用户,获取他们的推文时间线,仅过滤前 20 条推文,应用自定义过滤器,并最终使用回调函数处理每条推文。

我猜测像这样设计良好的 API 应该像查询构建器(想想 ORM)一样工作,其中每个函数调用都构建查询(在这种情况下为 HTTP URL),直到它遇到诸如 each/map/etc 之类的循环函数,进行 HTTP 调用,传入的函数成为回调。

一个简单的开发路线是使每个 AJAX 调用同步,但这可能不是最好的解决方案。我有兴趣找出一种使其异步的方法,并且仍然隐藏 AJAX 的异步性质。

请您参考如下方法:

看看几天前由 Twitter 工程师 Dustin Diaz 在@anywhere 上发表的以下文章:

  • Asynchronous method queue chaining in JavaScript

  • 他谈到了一种非常好的技术,它允许您在异步方法上实现流畅的接口(interface),基本上方法链接在一起独立于回调,使用非常简单的队列实现。