您的位置:首页 > Web前端 > JavaScript

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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: