Fork me on GitHub

How 'Promise' implemented?

Preface

Before you read, I hope you should have some hand-on experience of the Promise mechenism in javascript. And you should also bear in mind that Promise is not mysterious at all, which is just a trick invented by some functional programming enthusiast. In the following part, I will unmask the magic of this magic Promise

Anatomy

Recap

Let’s coin a simple promise example first

1
2
3
4
5
6
7
8
9
10
11
function getUserId() {
return new Promise(function(resolve){
http.get(url, function(results){
resolve(results.id);
})
});
}

getUserId().then(function(id){
//Processing given id from resolve;
});

Prototype for 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
61
62
63
64
65
66
67
68
69
70
71
72
73
function Promise(fn) {
var state = 'pending';
var value = null;
var callbacks = [];

//'then' is a register for callbacks function
this.then = function (onFulfilled, onRejected){
return new Promise(function(resolve, reject){
handle({
onFulfilled: onFulfilled || null,
onRejected: onRejected || null,
resolve: resolve,
reject: reject
});
});
};

function handle(callback){
if (state == 'pending'){
callbacks.push(callback);
return;
}

var cb = (state === 'fulfilled' ? callback.onFulfilled: callback.onRejected);

if (cb === null) {
cb = (state === 'fulfilled' ? callback.resolve : callback.reject);
cb(value);
return;
}

try {
var ret = cb(value);
callback.resolve(ret);
} catch (e) {
callback.reject(e);
}

r
}


function resolve(newValue){
if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
var then = newValue.then;
if (typeof then === 'function') {
then.call(newValue, resolve);
return;
}
}
value = newValue;
state = 'fulfilled';
execute();
};

function reject(reason) {
state = 'rejected';
value = reason;
execute();
}


function execute(){
setTimeout(function() {
callbacks.forEach(function (callback){
callback(value);
});
}, 0);
}

//Start the real function call
fn(resolve, reject);
}