Search code examples
javascriptes6-promise

Memory leak in promise


I'm trying to implement a function utilizing promise that waits first then log some strings, the first thing pops in mind is clearTimeout when thinking about setTimeout, the function does what I intend to. My question is are there any memory leaks in the initial promise created which is ever pending since I clear the timeId so it's never gonna be settled.

Sorry for my bad English and messy code.

// Goodman
function Goodman(sbd) {
  let timeId

  let promise = new Promise(resolve => {
    timeId = setTimeout(() => resolve(console.log('I am ' + sbd)), 0)
  })

  let rest = function(ms) {
    this.promise.then(() => new Promise(resolve => setTimeout(resolve, ms)))
    return this
  }

  let learn = function(sth) {
    this.promise.then(() => console.log('Learning ' + sth))
    return this
  }

  let restFirst = function(ms) {
    clearTimeout(this.timeId)
    this.promise = new Promise(resolve => {
      this.timeId = setTimeout(resolve, ms)
    }).then(() => console.log('I am ' + sbd))
    return this
  }

  return {
    timeId,
    promise,
    rest,
    learn,
    restFirst
  }
}

// Initially wait 5 seconds
// "I am Tom"
// "Learning chinese"
Goodman('Tom')
  .restFirst(5000)
  .learn('chinese')

Solution

  • My question is are there any memory leaks in the initial promise created which is ever pending since I clear the timeId so it's never gonna be settled.

    No, a promise that is never resolved or rejected is just an object in Javascript like any other object. It will be garbage collected when there is no longer any code that has a reference to the object (when it becomes "unreachable").

    Remember, promises are just a notification system. All they are is a regular Javascript object that serves as clearinghouse for success and failure listeners and a latched success value or failure reason for some event that completes some time in the future. They are just an object with methods like any other object. When, they become unreachable, they will be garbage collected at that time whether they are resolved, rejected or still pending.