一个Promise的简单实现

example

什么是Promise

Promise就是抽象异步处理对象以及对其进行各种操作的组件。比较土的说法就是,提高多从回调带来的代码可阅读性。

一个简单的实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
function Promise() {
this.callbacks = [];
}
Promise.prototype = {
constructor: Promise,
resolve: function(result) {
this.complete('resolve', result);
},
reject: function(result) {
this.complete('reject', result);
},
complete: function(type, result) {
while(this.callbacks[0]) {
this.callbacks.shift()[type](result);
}
},
then: function(successHandle, errorHandle) {
this.callbacks.push({
resolve: successHandle,
reject: errorHandle
});
}
};
//使用
var promise = new Promise();
var delay1 = function() {
setTimeout(function() {
promise.resolve('hello world');
}, 1000);
return promise;
}
delay1()
.then(function(re) {
var re = re + ' Angular';
console.log(re);
promise.resolve(re);
});