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

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

问题描述

我将如何设计一个API隐藏AJAX和HTTP请求的异步特性,或基本延缓它提供了流畅的界面。要显示来自Twitter的新一个例子任何地方 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(异步每次通话的本质是清晰可见)

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应该像一个查询生成器(想想奥姆斯),其中每个函数调用建立查询(HTTP URL在这种情况下),直到达到一个循环的功能,如每个/图/等,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.

推荐答案

给看看公布的只是一对夫妇的天前达斯汀·迪亚兹,在@anywhere Twitter的工程师下面的文章:

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天全站免登陆