-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
122 lines (109 loc) · 2.59 KB
/
index.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
/*
* Simple Promise implementation
* Author: Edgar Marukyan
* Company: Peyotto Technologies
* TODO: Add Promise.all, Promise.each, Promise.coroutine
*/
// Self implementation of promise!
var Promise = function (callback) {
var self = this
this.__error
this.__result
this.resolve = function (result) {
self.__result = result
return this
}
this.reject = function (err) {
console.log(' this.reject')
self.__error = err
return self
}
this.then = function (tCallback) {
console.log(' this.then')
if (self.__error) {
return self
}
self.__result = tCallback(self.__result)
return self
}
this.catch = function (cCallback) {
console.log(' this.catch')
if (self.__error) {
cCallback(self.__error)
}
return self
}
this.__initialCall = function () {
console.log(' this.__initialCall')
callback(self.resolve, self.reject)
return this
}
return this.__initialCall()
}
Promise.all = function (promises) {
return new Promise(function (resolve, reject) {
var rejected = false
var pending = promises.length
var results = new Array(pending)
promises.map((promise, i) => {
promise().then(function (result) {
--pending
results[i] = result
if (!pending) {
resolve(results)
}
}).catch(function (err) {
pending = Infinity
if (rejected) {
// do nothing
} else {
rejected = true
reject(err)
}
})
})
})
}
// Assume we have some callback function that sometimes returns error
function someCallBackFunction (options, cb) {
if (parseInt(Math.random() * 10, 10) % 2 === 0) {
var data = {status: 'ok'}
cb(null, data)
} else {
cb('Something wired happened!')
}
}
// Let's promisify this function
function callbackFunction2Promise () {
return new Promise(function (resolve, reject) {
someCallBackFunction({}, function (err, data) {
if (err) {
reject(new Error(err))
} else {
resolve(data)
}
})
})
}
// Call it !
callbackFunction2Promise().then(data => {
console.log(data)
}).then(data => {
console.log(data) // undefined, cos nothing is returned from previous then
return 1
}).then(data => {
console.log(data) // 1
}).catch(err => {
console.log(err.stack)
})
// Promise all test!
Promise.all([
callbackFunction2Promise,
callbackFunction2Promise,
callbackFunction2Promise]).then(results => {
console.log('Promise All results')
console.log(results)
}).catch(err => {
console.log('Promise All err')
console.log(err)
})