如果Promise重复等待永远不解决,会导致内存泄漏吗?

huangapple go评论56阅读模式
英文:

If Promises Repeatedly Awaited Never Resolve, Does It Cause a Memory Leak?

问题

If repeatedly awaited (or .then()ed) promises never resolve, will all the promises and execution contexts eventually be garbage collected or will it cause a memory leak?

e.g.

async function whatHappens() {
  await neverResolves();
  doSomething();
}

function neverResolves() {
  return new Promise(() => {});
}

function doSomething() {
  console.log('never happening');
}

// main thread
for (/* very long loop */) {
  whatHappens();
}

我理解,即使挂起的 promise 如果没有引用将被垃圾回收,但不确定等待它是否会被视为一个“引用”,从而阻止整个垃圾回收过程,使暂停的函数保留在内存中。或者它是否仍然会发生,并且暂停的函数也会被垃圾回收。

一个有经验的人类回答会很有帮助。谢谢提前。

英文:

If repeatedly awaited (or .then()ed) promises never resolve, will all the promises and execution contexts eventually be garbage collected or will it cause a memory leak?

e.g.

async function whatHappens() {
  await neverResolves();
  doSomething();
}

function neverResolves() {
  return new Promise(() => {});
}

function doSomething() {
  console.log('never happening');
}


// main thread
for (/* very long loop */) {
  whatHappens();
}

I understand even a hung promise will be garbage collected if there are no references to it, but I'm not sure if awaiting it will count as a "reference" thus preventing the whole garbage collection process and leaving in memory paused functions. Or whether it will still happen and the paused functions will also be garbage collected.

A knowledgeable human response would be appreciated.
Thanks in advance.

答案1

得分: 1

No. 相反,await 不会创建一个对暂停函数的引用,而是从 promise 到暂停函数的引用 - 函数的继续执行会被注册为 promise 处理程序(即 .then() 调用)。

因此,如果 promise 从未被解决,而且没有更多的引用指向它(包括可能解决它的解析器函数),那么这个 promise 和暂停的函数都将被垃圾回收。

英文:

> I'm not sure if awaiting it will count as a "reference"

No. On the contrary, await does not create a reference to the promise from the paused function but rather from the promise to the paused function - the resumption of the function is registered as a promise handler (i.e. .then() call).

So if the promise is never settled and there are no more references to it (including resolver functions that could settle it), both the promise and the paused function will get garbge-collected.

huangapple
  • 本文由 发表于 2023年6月1日 10:16:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76378279.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定