设计一个流畅的 Javascript 接口来抽象出 AJAX 的异步特性 [英] Designing a fluent Javascript interface to abstract away the asynchronous nature of AJAX

查看:29
本文介绍了设计一个流畅的 Javascript 接口来抽象出 AJAX 的异步特性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何设计 API 来隐藏 AJAX 和 HTTP 请求的异步特性,或者基本上延迟它以提供流畅的界面.展示来自 Twitter 的新 Anywhere API 的示例:

How would I design an API to hide the asynchronous nature of AJAX and HTTP requests, or basically delay it to provide a fluent interface. To show an example from Twitter's new 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/);
}

vs this(每次调用的异步性质清晰可见)

vs this (asynchronous nature of each call is clearly visible)

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 条推文,应用自定义过滤器,并最终使用回调函数处理每条推文.

It finds the user, gets their tweet timeline, filters only the first 20 tweets, applies a custom filter, and ultimately uses the callback function to process each tweet.

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

I am guessing that a well designed API like this should work like a query builder (think ORMs) where each function call builds the query (HTTP URL in this case), until it hits a looping function such as each/map/etc., the HTTP call is made and the passed in function becomes the callback.

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

An easy development route would be to make each AJAX call synchronous, but that's probably not the best solution. I am interested in figuring out a way to make it asynchronous, and still hide the asynchronous nature of AJAX.

推荐答案

请看几天前 Twitter 工程师达斯汀·迪亚兹 (Dustin Diaz) 在 @anywhere 上发表的以下文章:

Give a look to the following article published just a couple of days ago by Dustin Diaz, Twitter Engineer on @anywhere:

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

He talks about a really nice technique that allows you to implement a fluent interface on asynchronous methods, basically methods chained together independent of a callback, using a really simple Queue implementation.

这篇关于设计一个流畅的 Javascript 接口来抽象出 AJAX 的异步特性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆