JavaScript异步编程之:改造世界上最短的Promise库。。。
2013-02-25 14:15
323 查看
看了这篇文章:javascript异步编程之:世界上最短的Promise库,这个虽然短,但是我觉得不是很好用,有个不足:每个函数里都要实例化一个Promise对象,完全没必要。所以花了几分钟改写了下,还增加了给then方法直接传多个函数的特性,直接看代码吧:
<!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html;charset=utf-8"> <title>Promise</title> </head> <body> <br/>Pomise <script type="text/javascript"> //单例模式 (function(){ var promise, _promise = function(){ this.thens = []; }; _promise.prototype = { resolve: function(){ var t = this.thens.shift(); t && t.apply(null, arguments); }, then: function(){ return this.thens.push.apply(this.thens, arguments), this; } }; window.Promise= function(){ return promise || (promise = new _promise()); }; })(); var promise = Promise(); function f1() { setTimeout(function () { alert(1); promise.resolve(); }, 1500); } function f2() { setTimeout(function () { alert(2); promise.resolve(); }, 1500); } function f3() { setTimeout(function () { alert(3); promise.resolve(); }, 1500); } function f4() { alert(4); } //用法一: //promise.then(f1).then(f2).then(f3).then(f4).resolve(); //用法二: promise.then(f1, f3, f2, f4).resolve(); //promise.then(f1, f3).then(f2).then(f4); promise.resolve(); </script> </body> </html>
相关文章推荐
- javascript异步编程之:世界上最短的Promise库
- 码农干货系列【6】--javascript异步编程之:世界上最短的Promise库
- 世界上最短的DVD解码程序(附源码)
- zz世界上最短的小说
- 世界上最短的一本书:关于"缺陷"和"满足"的寓言
- 一个被称为世界上最短的判断IE方法
- 世界上最短的DVD解码程序
- 世界上最短的数字判断代码
- 世界上最短的数字判断代码
- 世界上最短的时钟代码!更短的,有木有?
- 世界上最短的病毒
- 世界上最短的时钟代码!更短的,有木有?
- 世界上最短的DVD解码程序(<0.5K)
- 世界上最短的小说
- 世界上最短的时钟代码!更短的,有木有?
- 遗留系统升级改造方案思路
- 数据结构学习笔记05图 (邻接矩阵 邻接表-->BFS DFS、最短路径)
- 【图论初步】最短路径与条数
- Dijkstra算法(单源最短路径)
- 迷宫问题并求最短路径