-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcallback-2-promise.js
74 lines (65 loc) · 1.59 KB
/
callback-2-promise.js
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
74
module.exports = function Callback2Promise() {
this.defer = null;
this.promise = null;
this.isFulfiled = false;
this.isRejected = false;
this.fulfillData = null;
this.errorData = null;
var _resolve = function (self, result) {
if (self.defer && self.defer.resolve) {
self.defer.resolve(result);
}
self.fulfillData = result;
}
var _reject = function (self, result) {
if (self.defer && self.defer.reject) {
self.defer.reject(result);
}
self.errorData = result;
}
this.getFulfillCallback = function () {
var self = this;
return function (result) {
self.isFulfilled = true;
_resolve(self, result);
}
}
this.getErrorCallback = function () {
var self = this;
return function (result) {
self.isRejected = true;
_reject(self, result);
}
}
this.getPairCallback = function () {
var self = this;
return function (error, data) {
if (error) {
self.isRejected = true;
_reject(self, error);
} else {
self.isFulfilled = true;
_resolve(self, data);
}
}
}
this.go = function go() {
var self = this;
if (!this.promise) {
this.promise = new Promise(function(resolve, reject) {
self.defer = {
resolve: resolve,
reject: reject
};
});
// If callback was called before creating Promise
if (this.isFulfilled) {
this.defer.resolve(this.fulfillData);
} else if (this.isRejected) {
this.defer.reject(this.errorData);
}
}
return this.promise;
}
return this;
}