This repository has been archived by the owner on Jan 19, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
106 lines (84 loc) · 2.4 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
'use strict'
// ===================================================================
function noop () {}
function makeEventAdder (emitter, arrayArg) {
var addListener =
emitter.addEventListener ||
emitter.addListener ||
emitter.on
if (!addListener) {
throw new Error('cannot register an event listener')
}
var removeListener =
emitter.removeEventListener ||
emitter.removeListener ||
emitter.off
var eventsAndListeners = []
var cleanUp = removeListener
? function () {
for (var i = 0, n = eventsAndListeners.length; i < n; i += 2) {
removeListener.call(emitter, eventsAndListeners[i], eventsAndListeners[i + 1])
}
}
: noop
function addEvent (event, cb) {
function listener () {
cleanUp()
var arg
var n = arguments.length
if (arrayArg) {
arg = new Array(n)
for (var i = 0; i < n; ++i) {
arg[i] = arguments[i]
}
arg.event = event
} else {
arg = n > 0 ? arguments[0] : undefined
}
cb(arg)
}
eventsAndListeners.push(event, listener)
addListener.call(emitter, event, listener)
}
addEvent.cleanUp = cleanUp
return addEvent
}
// ===================================================================
function eventToPromise (emitter, event, opts) {
var cancel
var promise = new Promise(function (resolve, reject) {
var addEvent = makeEventAdder(emitter, opts && opts.array)
cancel = function () {
cancel = noop
addEvent.cleanUp()
}
addEvent(event, resolve)
if (!opts || !opts.ignoreErrors) {
addEvent((opts && opts.error) || 'error', reject)
}
})
promise.cancel = function () { return cancel() }
return promise
}
var defaultErrorEvents = [ 'error' ]
eventToPromise.multi = function eventsToPromise (emitter, successEvents, errorEvents) {
errorEvents || (errorEvents = defaultErrorEvents)
var cancel
var promise = new Promise(function (resolve, reject) {
var addEvent = makeEventAdder(emitter, true)
cancel = function () {
cancel = noop
addEvent.cleanUp()
}
var i, n
for (i = 0, n = successEvents.length; i < n; ++i) {
addEvent(successEvents[i], resolve)
}
for (i = 0, n = errorEvents.length; i < n; ++i) {
addEvent(errorEvents[i], reject)
}
})
promise.cancel = function () { return cancel() }
return promise
}
module.exports = eventToPromise