0

I have a relatively simple example for you to explain the weird issue I'm seeing:

    this.applyActions = function (name, arg1, arg2, arg3, arg4, arg5, arg6) {

        var promise = new RSVP.Promise(function (resolve, reject) {
            // resolve all the functions
            RSVP.hashSettled(this.actions[name])
                //if it fails, just resolve to an empty object
            .catch(function (reason) {
                resolve({});
            })
                //resolve the functions into their promises, as designed
            .then(function (funcs) {
                for (var key in funcs) {
                    console.log(key);
                    funcs[key] = funcs[key].value(arg1, arg2, arg3, arg4, arg5, arg6);
                }
                return funcs;
            })
                //fulfill all the promises to get the results
            .then(function (promises) {
                return RSVP.hashSettled(promises);
            }, function (reason) { console.log(reason); })
            .then(function (results) {
                resolve(results);
            });;
        }.bind(this));

        return promise;
    };

Basically, when rsvp does it's thing, it may be quite some time (300 ms or more) between defining and resolving the function. In other words, by the time we've reached the the part where the functions are resolved, function ApplyAction arguments have lost their scope and have been garbage collected.

I've been wracking my brain trying to think of a way to either prevent GC (and keep my closures) or get the arguments to the anonymous functions.

Does anyone have an idea on how to solve this?

  • Where I say, defining, I mean the entry point, or first promise resolved. – Rob Landers Jan 09 '14 at 22:12
  • Garbage collection never happens on data that is referenced somewhere in the program. If you're talking about this: `funcs[key].value(arg1, arg2, arg3, arg4, arg5, arg6);`, then the anonymous function will create a closure and be able to reference those parameters. – cookie monster Jan 09 '14 at 22:17
  • That is the line I'm referring to and why I'm completely confused as to why the functions are being passed undefined variables. – Rob Landers Jan 09 '14 at 22:26
  • Did you `console.log(arg1, arg2, arg3, arg4, arg5, arg6);` at the top of the `.applyAction` method? If values were passed, your anonymous function will close over them. – cookie monster Jan 09 '14 at 22:27
  • Don't I feel dumb ... turns out the arguments were referenced via a for loop that already completes before this function is called, so when it tries to call the function with arr[2], it is in fact undefined (there's no arr[2]). Damn asynchronous methods ... – Rob Landers Jan 09 '14 at 22:33
  • Glad you got it figured out. – cookie monster Jan 09 '14 at 22:36

0 Answers0