-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpromise-race.js
108 lines (98 loc) · 2.61 KB
/
promise-race.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
const Promise = require('finished-promise')
module.exports = describe => {
describe(
() => new PromiseRace(
new Promise(resolve => resolve(1)),
new Promise(resolve => resolve(2))
),
describe(
'when promise 1 finishes',
race => race.whenNthFinishes(1),
it => it.has('result').that.equals(1),
describe(
'then promise 2 finishes',
race => race.whenNthFinishes(2),
it => it.has('result').that.equals(1)
)
),
describe(
'when promise 2 finishes',
race => race.whenNthFinishes(2),
it => it.has('result').that.equals(2),
describe(
'then promise 1 finishes',
race => race.whenNthFinishes(1),
it => it.has('result').that.equals(2)
)
)
)
describe(
() => new PromiseRace(
new Promise(resolve => resolve(1)),
new Promise((resolve, reject) => reject(new Error('2')))
),
describe(
'when promise 1 finishes',
race => race.whenNthFinishes(1),
it => it.has('result').that.equals(1),
describe(
'then promise 2 finishes',
race => race.whenNthFinishes(2),
it => it.has('result').that.equals(1)
)
),
describe(
'when promise 2 finishes',
race => race.whenNthFinishes(2),
it => it.has('error').that.has('message').that.equals('2'),
describe(
'then promise 1 finishes',
race => race.whenNthFinishes(1),
it => it.has('error').that.has('message').that.equals('2')
)
)
)
}
function PendingPromise (underlyingPromise) {
underlyingPromise.then(result => {
this.result = result
})
underlyingPromise.catch(error => {
this.error = error
})
this.resolveHandlers = []
this.rejectHandlers = []
}
PendingPromise.prototype.finish = function () {
if (this.error) {
this.rejectHandlers.forEach(handler => handler(this.error))
} else {
this.resolveHandlers.forEach(handler => handler(this.result))
}
}
PendingPromise.prototype.then = function (resolveHandler) {
this.resolveHandlers.push(resolveHandler)
return this
}
PendingPromise.prototype.catch = function (rejectHandler) {
this.rejectHandlers.push(rejectHandler)
return this
}
function PromiseRace () {
let finished = false
this.promises = [].slice.apply(arguments).map(
p => new PendingPromise(p)
.then(result => {
if (!finished) this.result = result
finished = true
})
.catch(error => {
if (!finished) this.error = error
finished = true
})
)
}
PromiseRace.prototype.whenNthFinishes = function (n) {
this.promises[n - 1].finish()
return this
}