Can this function be garbage-collected?

空扰寡人 提交于 2019-12-04 00:39:00

There is nothing keeping reference to the promise so it will be garbage collected. The promise is the only thing keeping reference to the function doMoreWork so it will be garbage collected too.

How could I empirically observe this behaviour? In other words, how can I monitor what objects are being GC-ed and when? I develop purely in Node.js, if that makes any difference.

The GC in V8 never necessarily collects an object. For instance if this is your whole program, it would be a waste of time to run any GC in the first place.

  1. The Promise object is collectable if it has no references pointing to it. If it is used doWork().then(...) a temporary reference is created. So until .then does not block anymore there is a reference to the object so it cannot be collected
  2. You're right, doMoreWork is also not collectible because the Promiseobject has a reference to it

The statement doWork().then(...) can be replaced by

new Promise(function (resolve, reject) {
  // work work work...
}).then(function doMoreWork () {
          // Some more work to do...
        })

So you can imagine that you are using the Promiseobject directly, so the "Upper"-Scope is where the object is used.

Objects are generally collected when there are no more references to it. Even if the code is in a Promise it is just an object and the call to then is chained, so the object is being used

To see if an object is garbage-collectible you can create a test and look for memory leak (through task manager). If your code is written properly, everything gets collected.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!