`

JavaScript异步实现

阅读更多

Asynchronous method queue chaining in JavaScript

Thursday, May 6th, 2010

Chaining . It’s an extremely popular pattern these days in JavaScript. It’s easily achieved by continually returning a reference to the same object between linked methods. However one technique you don’t often see is queueing up a chain of methods,  asynchronously , by which functions can be linked together  independent of a callback . This discussion, of course, came from a late work night building the @anywhere  JavaScript API with two other mad scientists, Russ D’Sa (@dsa) and Dan Webb (@danwrong).

Anyway, let’s have a look at some historical conventions and compare them to newer ones.

Imagine an iterator class that operated on arrays. It could look like this:

// no chaining
var o = new Iter(['a', 'b', 'c', 'd', 'e']);
o.filter(function(letter) {
  if (letter != 'c') { return letter; }
});
o.each(function(letter) {
  append(letter);
});

// with chaining
new Iter(alphabet).filter(remove_letter_c).each(append);

This is a simple because we’re working on a known existing object in memory (the alphabet array). However an easy way to spoil our soup is to make our methods continue to operate without existing objects. Like say, for example, a result set you had to make an async request to the server to get. Thus, imagine making this work:

ajax('/server/results.json').filter(remove_duplicates).append('div#results');

In the grand scheme of things, the above example isn’t too far off from from  currying   (which it’s not). And to make another point, currying can often lead to bad coupling of code… which in its defense, is often the point as well. Some libraries even call this pattern  binding … so… yeah.

Anyway, to the point, here is a basic Queue implementation that can be used as a tool to build your own asynchronous method chains.

function Queue() {
  // store your callbacks
  this._methods = [];
  // keep a reference to your response
  this._response = null;
  // all queues start off unflushed
  this._flushed = false;
}

Queue.prototype = {
  // adds callbacks to your queue
  add: function(fn) {
    // if the queue had been flushed, return immediately
    if (this._flushed) {
      fn(this._response);

    // otherwise push it on the queue
    } else {
      this._methods.push(fn);
    }
  },

  flush: function(resp) {
    // note: flush only ever happens once
    if (this._flushed) {
      return;
    }
    // store your response for subsequent calls after flush()
    this._response = resp;
    // mark that it's been flushed
    this._flushed = true;
    // shift 'em out and call 'em back
    while (this._methods[0]) {
      this._methods.shift()(resp);
    }
  }
};

With this code, you can put it straight to work for something useful, like say, a jQuery plugin that fetches content remotely and then appends the results to your selector input. For you plugin developers our there, it would look like this…

<script src="jquery.js"></script>
<script src="async-queue.js"></script>
<script>
(function($) {

  $.fn.fetch = function(url) {
    var queue = new Queue;

    this.each(function() {
      var el = this;
      queue.add
(function(resp) {
        $(el).html(resp);
      });
    });

    $.ajax({
      url: url,
      dataType: 'html',
      success: function(html) {
        queue.flush(html);

      }
    });
    return this;
  };

})(jQuery);
</script>

Then voila! You can make your DOM queries, fetch remote content, and continue your chain, asynchronously.

$("<div/>")
  .fetch('/server/navigation.html')
  .addClass('column')
  .appendTo('#side');

Here’s a  brief example   of showing off the example above. Point being, one can only imagine the possibilities you could do. Say for example, having multiple items in the queue waiting to operate on a response. Thus imagine this…

fetchTweet(url).linkify().filterBadWords().appendTo('#status');

Your internals would look like this with the Queue.

function fetchTweet(url) {
  this.queue = new Queue;
  this.tweet = "";
  var self = this;
  ajax(url, function(resp) {
    self.tweet = resp;
    self.queue.flush(this);
  });
}
fetchTweet.prototype = {

  linkify: function() {
    this.queue.add(function(self) {
      self.tweet = self.tweet.replace(/\b@(\w{1,20}\b/g, '<a href="...">$1</a>');
    });
  return this;
  },

  filterBadWords: function() {
    this.queue.add(function(self) {
      self.tweet = self.tweet.replace(/\b(fuck|shit|piss)\b/g, "");
    });
  return this;
  },

  appendTo: function(selector) {
    this.queue.add(function(self) {
      $(self.tweet).appendTo(selector);
    });
  return this;
  }

};

And with that, you can call it a night. Cheers.

 

原文:http://www.dustindiaz.com/async-method-queues/

分享到:
评论

相关推荐

    Javascript异步编程(英文版)

    《JavaScript异步编程》这本书深入探讨了现代JavaScript开发中的关键主题——如何在不陷入混乱的情况下处理并发和并发任务。本书作者Trevor Burnham通过精确平衡的浏览器端和服务器端示例,为读者提供了一份简洁的...

    JavaScript异步编程g.pdf

    JavaScript异步编程是前端开发领域中的一个重要概念,它允许程序在等待长时间操作(如网络请求)时继续执行其他任务,而不是简单地暂停或停止,从而提升用户体验。本书《JavaScript异步编程》作为图灵程序设计丛书的...

    Javscript高性能编程+Javascript异步编程

    "JavaScript高性能编程"和"JavaScript异步编程"是两个关键的JavaScript专题,对于提升应用程序的性能和用户体验至关重要。 一、JavaScript高性能编程 1. **优化代码执行效率**:了解JavaScript引擎的工作原理,如...

    深入理解JavaScript异步

    JavaScript异步编程是Web开发中的核心概念,尤其在构建高性能、响应式的网页应用时不可或缺。深入理解这一主题,对于任何JavaScript开发者来说都是至关重要的。在这个教程中,我们将探索JavaScript异步处理的各个...

    JavaScript设计模式+JavaScript模式+JavaScript异步编程

    3. **JavaScript异步编程**: 异步编程是JavaScript的重要特性,用于处理耗时操作,如网络请求和文件读写,以避免阻塞主线程。主要方法有: - 回调函数:最基础的异步处理方式,但可能导致回调地狱问题。 - 事件...

    Javascript异步编程的4种方法

    ### JavaScript异步编程的四种方法 #### 概述 JavaScript是一种广泛使用的脚本语言,尤其在Web开发领域占据着核心地位。由于浏览器环境的限制,JavaScript最初被设计为单线程执行模型。这意味着在同一时间只能执行...

    浅析JavaScript异步代码优化

    JavaScript异步代码优化是开发过程中不可或缺的一环,尤其是在前端开发中,由于JavaScript的单线程特性,异步处理显得尤为重要。本文将深入探讨JavaScript异步编程的问题及其优化策略。 首先,我们来关注最常见的一...

    javascript异步调用库

    实现javascript异步调用 API: window.asyncall(function/functionName[,args,...][,function callback]) 参数说明: function/functionName:方法或方法名称 args:目标方法参数 callback:回调函数...

    JavaScript异步编程学习

    博客中提到的“源码”和“工具”标签可能意味着作者深入探讨了JavaScript异步编程的实现原理,或者介绍了某些辅助开发的工具或库,比如Promise库bluebird或async/await的polyfill。代码文件可能包含了示例代码或练习...

    JavaScript异步编程

    JavaScript异步编程是前端开发中的重要概念,它允许在执行长时间运行的任务时不会阻塞主线程,从而提升用户体验。异步编程的核心在于,它不会立即得到结果,而是在某个未来的时刻,当任务执行完毕后,才会得到通知。...

    藏经阁-JavaScript异步编程.pdf

    藏经阁-JavaScript异步编程 JavaScript异步编程是JavaScript语言的一大特点,它可以使得JavaScript语言在单线程的情况下,执行多个任务,而不需要阻塞其他任务。异步编程的解决方案有多种,包括回调函数、Promise、...

    12JavaScript异步Ajax与json总结.docx

    **JavaScript异步Ajax与JSON详解** 在Web开发中,JavaScript异步Ajax技术是不可或缺的一部分,它使得网页可以在不刷新整个页面的情况下与服务器进行数据交互,极大地提升了用户体验。JSON(JavaScript Object ...

    JavaScript 异步编程:基本指南.docx

    本文将深入讲解JavaScript异步编程的基础和高级概念,帮助开发者理解并掌握这一核心技能。 1. **异步编程的基本概念** 在JavaScript中,异步编程意味着某些操作不会阻塞程序的执行,而是以非阻塞的方式进行。这是...

    详解JavaScript异步编程中jQuery的promise对象的作用_.docx

    详解JavaScript异步编程中jQuery的promise对象的作用 Promise 对象是 JavaScript 异步编程中的一种重要概念,特别是在 jQuery 库中。Promise 对象的主要作用是解决异步编程中的回调地狱问题,提供了一种简洁的方式...

    goole map动态连线 javaScript 异步调用C#

    本话题主要关注如何使用JavaScript异步调用C#代码来实现在Google Map上动态连线的功能。下面我们将深入探讨这个主题。 首先,让我们了解动态连线在Google Map上的实现。动态连线通常指的是在地图上根据实时数据创建...

    【JavaScript源代码】JavaScript实现异步获取表单数据.docx

    ### JavaScript 实现异步获取表单数据 #### 一、背景介绍 在现代Web开发中,异步操作是一项非常重要的技术。它允许浏览器在等待服务器响应的同时继续...希望这些知识点能帮助您更好地理解和应用JavaScript异步操作。

    flash javascript 异步上传文件 --swfupload

    在现代Web应用中,文件上传是一项常见的功能,而“Flash JavaScript异步上传文件——SWFUpload”正是这种功能的一种实现方式。SWFUpload是一个开源的JavaScript库,它结合了Adobe Flash技术,允许用户在不刷新整个...

    Ajax页面局部异步刷新技术

    其中,最典型的技术就是Ajax(Asynchronous JavaScript and XML),它可以实现页面局部的异步刷新。 #### XMLHttpRequest对象简介 在给定的示例代码中,我们首先创建了一个`XMLHttpRequest`对象。`XMLHttpRequest`...

Global site tag (gtag.js) - Google Analytics