try to write a simple Promise implementation

接触Promise感觉已经挺久了,虽然我感觉Callback嵌套不深的话还是可以接受的,不会刻意的使用Promise。不过我一直没有试过Promise是怎么实现的,今晚尝试了下怎么实现Promise。

一开始写的是个简单的实现,只有then,catch,不能链式调用,这样我感觉Promise最大的优势就没有了,所以我仔细想了下怎么才能实现promise chain,下面直接上代码:

实现:

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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60

function Promise (asyn){
let self = this;
this.handleError = null;
this.handleSuccess = [];

function resolve() {
let index = 0;

function next (){
try {

let returnValue = self.handleSuccess[index].apply({}, arguments);

index++;

if (self.handleSuccess[index]){
if (returnValue instanceof Promise){

let handleSuccess = returnValue.handleSuccess;
handleSuccess.push.apply(handleSuccess, self.handleSuccess.splice(index));
returnValue.handleError = self.handleError;
}
else {
next(returnValue);
}
}

} catch (error) {
reject(error);
}

}

next.apply({}, arguments);
}
function reject() {
self.handleError.apply({},arguments);
}

try {
asyn(resolve, reject);
} catch (error) {
reject(error);
}
}

Promise.prototype.then = function (funA, funB) {
this.handleSuccess.push(funA);
this.handleError = funB;

return this;
}

Promise.prototype.catch = function (handleError) {
this.handleError = handleError;
}

module.exports = Promise;

例子:

Usage
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

let Promise = require("./promise")

let timeout = function (delay) {
return new Promise(function (resolve, reject){
setTimeout(function (){
resolve("success");
}, delay);
})
}

timeout(2000).then((args) => {
console.log(args);
return "first then done"
})
.then((args) => {
console.log(args);
return timeout(1500);
})
.then((args) => {
console.log(args);
throw new Error("throw an error");
})
.catch((error) => {
console.log("got an error:",error);
})

感觉自己的写法不太好,只实现了简单的cascade,准备之后参考下Promise库的实现。可以对比下别人和自己的思路。

明天还要搬砖,不能修仙了。