1
1
const handlers = { }
2
2
, last = [ ]
3
3
4
- let exitPromise = Promise . resolve ( )
5
- , finished = false
4
+ let finished = false
6
5
7
6
export default prexit
8
7
@@ -24,10 +23,15 @@ function prexit(signals, fn) {
24
23
prexit . signals = [ 'beforeExit' , 'uncaughtException' , 'unhandledRejection' , 'SIGTSTP' , 'SIGQUIT' , 'SIGHUP' , 'SIGTERM' , 'SIGINT' ]
25
24
prexit . logExceptions = true
26
25
27
- prexit . last = fn => last . push ( fn )
26
+ prexit . last = addLast
28
27
prexit . exit = exit
29
28
prexit . ondone = ondone
30
29
30
+ function addLast ( fn ) {
31
+ last . length || prexit ( ( ) => { } )
32
+ last . push ( fn )
33
+ }
34
+
31
35
function exit ( signal , code , error ) {
32
36
if ( typeof signal === 'number' ) {
33
37
error = code
@@ -42,7 +46,6 @@ function exit(signal, code, error) {
42
46
}
43
47
44
48
function ondone ( signal , error ) {
45
- error && console . error ( error ) // eslint-disable-line
46
49
process . exit ( ) // eslint-disable-line
47
50
}
48
51
@@ -53,16 +56,20 @@ function handle(signal, fn) {
53
56
54
57
const fns = handlers [ signal ] = [ fn ]
55
58
56
- process . on ( signal , function ( error ) {
59
+ process . on ( signal , async function ( error ) {
57
60
error === signal && ( error = null )
58
61
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
+ }
60
71
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 )
66
73
} )
67
74
}
68
75
0 commit comments