title: Resolving a promise in a Socket.io callback returns a reference to a variable that doesn't get garbage collected
body: <p>Here is the code in question. It functions normally except for two specific things:</p>
  <p>(1) If I include the <code>delete b.x</code> and <code>delete b.y</code>, the function that uses this function's result errs when those fields are at that point <code>undefined</code>. I'm assuming this is because it's passing a reference to the object. Normally I would just make a copy of <code>b</code> and resolve with that, but that brings me to the next problem:</p>
  <p>(2) There seems to be a serious memory leak in which I run the memory profiler on chrome and I see multiple GB being retained over many uses of this function. When I look at the specific objects being retained, <code>b</code> is clearly being retained even though the promise has been resolved. This is consistent with the fact that <code>delete b.x</code> is causing an error even after resolution.</p>
  <pre><code>const streamTrainBatch = (
      trainConfig,
      socket: typeof Socket
    ): Promise&lt;{ x: any[]; y: any[] }&gt; =&gt;
      new Promise((resolve) =&gt; {
        // stream batch_size arrays and concatenate them along batch axis (0)
  
        const batch_ids: any = trainConfig.fileIds.train.slice(
          0,
          trainConfig.batchSize
        );
        const new_batch: any = { x: [], y: [] };
        let xs = [];
        let ys = [];
        let totalBatchesGotten = 0;
  
        for (const idToGet of batch_ids) {
          if (socket) {
            socket.emit(&quot;stream data&quot;, {
              dataset: trainConfig.datasetName,
              split: &quot;train&quot;,
              fileID: idToGet,
            });
          }
        }
  
        if (socket) {
          socket.on(&quot;data&quot;, (data: Buffer) =&gt; {
            let [x, y] = processRawData(data);
  
            if (x &amp;&amp; y) {
              //new_batch[&quot;x&quot;].push(x[0][0]); // remove the batch axis (unitary) and... other axis lol
              //new_batch[&quot;y&quot;].push(y[0][0]);
              xs.push(x[0][0]);
              ys.push(y[0][0]);
  
              totalBatchesGotten += 1;
  
              if (totalBatchesGotten &gt;= batch_ids.length) {
                const b = { x: [...xs], y: [...ys], debug: &quot;true&quot; };
                //new_batch.x = [];
                //new_batch.y = [];
                xs = [];
                ys = [];
  
                resolve(b);
                delete b.x;
                delete b.y;
              }
            }
            return;
          });
        }
      });
  </code></pre>
  <p>How do I make sure that <code>b</code> gets garbage collected?</p>
  <p>I could really use some help here as I've spent the past 2 days working on this and can't seem to get anywhere.
  Thanks!</p>