Does JavaScript promise create memory leaks when not rejected or resolved?

I’m in a situation where I need execute async functions in “parallel”, and continue program execution with the best result. Thus I wrote something like this :

var p = [];

for (var i = 0; i < 10; ++i) (function (index) {
  p.push(new Promise(function (resolve, reject) {
    setTimeout(function () {
      var success = Math.random() > 0.7;

      console.log("Resolving", index, "as", success ? "success" : "failure");

      success && resolve(index);
    }, Math.random() * 5000 + 200);
  }));
})(i);

Promise.race(p).then(function (res) {
  console.log("FOUND", res);
}).catch(function (err) {
  console.log("ERROR", err);
});

Now, I’m wondering if this is good practice when working with promises? Is not resolving or rejecting them more often then anything create memory leaks? Are they all eventually GC’ed every time?

  • What is the intention behind clause 2.2.4 of Promise/A+ spec?
  • chain array of promises with bluebird
  • How do I access previous promise results in a .then() chain?
  • Should a Promise.reject message be wrapped in Error?
  • How to propagate a reject in a ES6 Promise chain?
  • When shall one make a function return a promise?
  • How to polyfill fetch and promise with webpack 2?
  • Abort ecmascript7 async function
  • Javascript Promises explicit functions vs. inline functions
  • Does “resolve” consistently mean something distinct from “fulfill”?
  • How to have an async endless loop with Promises
  • How to use promise in forEach loop of array to populate an object
  • One Solution collect form web for “Does JavaScript promise create memory leaks when not rejected or resolved?”

    The only reason this will leak is because p is a global. Set p = null; at the end, or avoid using a global variable:

    var console = { log: function(msg) { div.innerHTML += msg + "<br>"; }};
    
    Promise.race(new Array(10).fill(0).map(function(entry, index) {
      return (function(index) {
        return new Promise(function(resolve) {
          setTimeout(function() {
            var success = Math.random() > 0.7;
            console.log((success? "R":"Not r") + "esolving "+ index +".");
            success && resolve(index);
          }, Math.random() * 5000 + 200);
        });
      })(index);
    })).then(function (res) {
        console.log("FOUND: " + res);
    }).catch(function (err) {
        console.log("ERROR: " + err);
    });
    <div id="div"></div>