-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
111 lines (73 loc) · 2.54 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
const promback = require('promback')
const timeoutable = require('timeoutable-wrapper')
function noop () {}
function using (PromiseLib) {
function defer () {
let resolve, promise
promise = new PromiseLib(function (_resolve) {
resolve = _resolve
})
return { resolve, promise }
}
const prombackProm = promback.using(PromiseLib)
const rmgr = function () {
const disposes = [], pending = []
let closing = null
const resources = {
add: async function (init, dispose) {
if (closing) { return }
try {
if (typeof init !== 'function') {
throw new Error('"init" must be a function.')
}
if (typeof dispose !== 'function') {
throw new Error('"dispose" must be a function.')
}
init = prombackProm(init)
dispose = prombackProm(dispose)
const initPromise = init()
pending.push(initPromise.then(noop, noop))
const resource = await initPromise
disposes.push(function () {
return dispose(resource)
})
return resource
} catch (err) {
try {
await resources.close()
} catch (closeErr) {
err.closeError = closeErr
}
throw err
}
},
close: async function () {
if (closing) { return closing.promise }
closing = defer()
await PromiseLib.all(pending)
let errs = []
while (disposes.length) {
try {
const dispose = disposes.pop()
await dispose()
} catch (err) {
errs.push(err)
}
}
closing.resolve()
if (errs.length) {
const e = errs.shift()
e.other = errs
throw e
}
},
}
return resources
}
const timeout = timeoutable.using(PromiseLib)
rmgr.timeout = timeout
rmgr.TimeoutError = timeoutable.TimeoutError
return rmgr
}
module.exports = using(Promise)
module.exports.using = using