作家
登录

javascript 支持链式调用的异步调用框架Async.Operation

作者: 来源:www.28hudong.com 2013-03-30 02:26:00 阅读 我要评论

复制代码 代码如下: Async = {}; Async.Operation = function(options) { options = options || {}; var callbackQueue = []; var chain = (options.chain && options.chain === true) ? true : false; var started = false; var innerChain = null; this.result = undefined; this.state = "running"; this.completed = false; this.yield = function(result) { var self = this; if (!chain) { self.result = result; self.state = "completed"; self.completed = true; } else { started = true; self.result = result; self.state = "chain running"; self.completed = false; } setTimeout(function() { if (!innerChain) { while (callbackQueue.length > 0) { var callback = callbackQueue.shift(); if (chain) { callbackResult = callback(self.result); self.result = callbackResult; if (callbackResult && callbackResult instanceof Async.Operation) { innerChain = Async.chain(); while (callbackQueue.length > 0) { innerChain.next(callbackQueue.shift()); } innerChain.next(function(result) { self.result = result; self.state = "completed"; self.completed = true; return result; }); callbackResult.addCallback(function(result) { self.result = result; innerChain.go(result); }); } } else { callback(self.result); } } if (!innerChain) { self.state = "completed"; self.completed = true; } } else { while (callbackQueue.length > 0) { innerChain.next(callbackQueue.shift()); } innerChain.next(function(result) { self.result = result; self.state = "completed"; self.completed = true; return result; }); } }, 1); return this; }; this.go = function(initialArgument) { return this.yield(initialArgument); } this.addCallback = function(callback) { callbackQueue.push(callback); if (this.completed || (chain && started)) { this.yield(this.result); } return this; }; this.next = function(nextFunction) { return this.addCallback(nextFunction); }; }; Async.chain = function(firstFunction) { var chain = new Async.Operation({ chain: true }); if (firstFunction) { chain.next(firstFunction); } return chain; }; Async.go = function(initialArgument) { return Async.chain().go(initialArgument); }

  推荐阅读

  JS 事件冒泡 示例代码

JS中的事件冒泡 目的当点击BBB的时候弹出TR,当点击AAA的时候弹出TD AAA BBB [Ctrl+A 全选 注:如需引入外部Js需刷新才能执行]>>>详细阅读


本文标题:javascript 支持链式调用的异步调用框架Async.Operation

地址:http://www.17bianji.com/kaifa2/JS/28325.html

关键词: 探索发现

乐购科技部分新闻及文章转载自互联网,供读者交流和学习,若有涉及作者版权等问题请及时与我们联系,以便更正、删除或按规定办理。感谢所有提供资讯的网站,欢迎各类媒体与乐购科技进行文章共享合作。

网友点评
自媒体专栏

评论

热度

精彩导读
栏目ID=71的表不存在(操作类型=0)