Skip to content

Commit d9c25b1

Browse files
committed
Fix last() and improve exit awaits
1 parent 3ea7dd1 commit d9c25b1

File tree

1 file changed

+18
-11
lines changed

1 file changed

+18
-11
lines changed

index.js

Lines changed: 18 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
const handlers = {}
22
, last = []
33

4-
let exitPromise = Promise.resolve()
5-
, finished = false
4+
let finished = false
65

76
export default prexit
87

@@ -24,10 +23,15 @@ function prexit(signals, fn) {
2423
prexit.signals = ['beforeExit', 'uncaughtException', 'unhandledRejection', 'SIGTSTP', 'SIGQUIT', 'SIGHUP', 'SIGTERM', 'SIGINT']
2524
prexit.logExceptions = true
2625

27-
prexit.last = fn => last.push(fn)
26+
prexit.last = addLast
2827
prexit.exit = exit
2928
prexit.ondone = ondone
3029

30+
function addLast(fn) {
31+
last.length || prexit(() => {})
32+
last.push(fn)
33+
}
34+
3135
function exit(signal, code, error) {
3236
if (typeof signal === 'number') {
3337
error = code
@@ -42,7 +46,6 @@ function exit(signal, code, error) {
4246
}
4347

4448
function ondone(signal, error) {
45-
error && console.error(error) // eslint-disable-line
4649
process.exit() // eslint-disable-line
4750
}
4851

@@ -53,16 +56,20 @@ function handle(signal, fn) {
5356

5457
const fns = handlers[signal] = [fn]
5558

56-
process.on(signal, function(error) {
59+
process.on(signal, async function(error) {
5760
error === signal && (error = null)
5861
if ((signal === 'uncaughtException' || signal === 'unhandledRejection') && prexit.logExceptions)
59-
console.error((error && 'stack' in error) ? error.stack : new Error(error).stack) // eslint-disable-line
62+
console.error(error) // eslint-disable-line
63+
64+
try {
65+
const xs = fns.map(fn => fn(signal, error)).filter(x => x && typeof x.then === 'function')
66+
xs.length && await Promise.all(xs)
67+
} catch (error) {
68+
process.exitCode || (process.exitCode = 1)
69+
prexit.logExceptions && console.error(error) // eslint-disable-line
70+
}
6071

61-
exitPromise = Promise.all(fns.map(fn =>
62-
Promise.resolve(fn(signal, error))
63-
).concat(exitPromise))
64-
.catch(() => process.exitCode || (process.exitCode = 1))
65-
.then(() => done(signal, error))
72+
done(signal, error)
6673
})
6774
}
6875

0 commit comments

Comments
 (0)