| 25 | * This gives a consistent way to dispose of objects that might be in a variety of states. |
| 26 | */ |
| 27 | export function finalize(...items: any[]): void { |
| 28 | for (const item of items) { |
| 29 | if (!item) { |
| 30 | return; |
| 31 | } |
| 32 | |
| 33 | // ensure that we're not finalizing the same item twice for no reason (or in a loop). |
| 34 | if (finalized.has(item)) { |
| 35 | continue; |
| 36 | } |
| 37 | |
| 38 | // store the value in the set so that we don't finalize it again. |
| 39 | finalized.add(item); |
| 40 | |
| 41 | if (item.finalize) { |
| 42 | try { |
| 43 | const result = item.finalize(); |
| 44 | if (is.promise(result)) { |
| 45 | // if the item has a finalize method, and it returns a promise, |
| 46 | // then we'll put the rest of the finalization on hold until that promise resolves. |
| 47 | // (this is useful when things need a few moments to stop (i.e. node:net:Server) |
| 48 | |
| 49 | const fin = result.catch(returns.undefined).then(() => { |
| 50 | ignore(() => item.end?.()); |
| 51 | ignore(() => item.stop?.()); |
| 52 | ignore(() => item.close?.()); |
| 53 | ignore(() => item.destroy?.()); |
| 54 | ignore(() => item.dispose?.()); |
| 55 | }); |
| 56 | ActiveFinalizers = Promise.all([fin, ActiveFinalizers, DispatcherBusy]).then(() => item.removeAllListeners?.()); |
| 57 | return; |
| 58 | } |
| 59 | } catch { |
| 60 | // ignore |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | // progressively call the various methods that might be available |
| 65 | // to tear down and release resources that might be held by the item. |
| 66 | ignore(() => item.end?.()); |
| 67 | ignore(() => item.stop?.()); |
| 68 | ignore(() => item.close?.()); |
| 69 | ignore(() => item.destroy?.()); |
| 70 | ignore(() => item.dispose?.()); |
| 71 | |
| 72 | // cleaning up listeners isn't as time critical, and it's possible there are some |
| 73 | // events that are still in the queue, so we'll do this asynchronously. |
| 74 | // and we expose the promise so that we can await it before exiting the process. |
| 75 | ActiveFinalizers = Promise.all([ActiveFinalizers, DispatcherBusy]).then(() => item.removeAllListeners?.()); |
| 76 | } |
| 77 | } |
| 78 | |