javascript recursive class: undefined method -
i have javascript class meant deal promises. first add functions array, executes them pops them , calls next one. @ end of array resolves promise. hope propagate resolution way stack of recursive calls. allow force multiple asynchronous functions run sequentially using simple set of commands. furthermore employ logic modify flow of ansync functions.
function sequencer() { this.functionsequence = []; this.addfunction = function (func) { this.functionsequence.push(func); } this.getfunctionsequence = function () { return functionsequence; } this.executeall = function () { var functionlist = this.functionsequence; var deferred = $q.defer(); if (functionlist.length > 0) { functionlist[0]().then(function (result) { if (result) { functionlist.splice(0, 1); executeall().then(function (resultinner) { if (resultinner == true) { deferred.resolve(true); } else { deferred.resolve(false); } }); } else { functionlist = []; deferred.resolve(false); } }); } else { deferred.resolve(true); } return deferred.promise; } } i getting referenceerror: 'executeall' undefined in script, on recursive call line "executeall' after splice
the first function in array being executed(i testing modal pop up) , when resolves hits splice, throws error right on executeall line. defining function incorrectly? calling correctly recursive function?
use this.executeall - assuming this correct, wont, you'll need account ... var self = this @ top of executeall, call self.executeall
this.executeall = function() { var functionlist = this.functionsequence; var deferred = $q.defer(); var self = this; // save reference if (functionlist.length > 0) { functionlist[0]().then(function(result) { if (result) { functionlist.splice(0, 1); // need use self here because "this" not "this" want self.executeall().then(function(resultinner) { if (resultinner == true) { deferred.resolve(true); } else { deferred.resolve(false); } }); } else { functionlist = []; deferred.resolve(false); } }); } else { deferred.resolve(true); } return deferred.promise; }; the reason this not this "want" due how this works in javascript - there plenty on info on stack exchange using this - i'll find , link answer shortly
i offer alternative code
this.executeall = function() { return this.functionsequence.reduce(function(promise, item) { return promise.then(function(result) { if (result) { return item(); } else { throw "fail"; // throw stop chain } }); }, promise.resolve(true)) .then(function(result) { this.functionsequence = []; // clear out added functions return true; // fulfilled value true per original code }.bind(this), function(err) { this.functionsequence = []; // clear out added functions if (err == "fail") { return false; // convert "fail" fullfilled value of false per original code } else { throw err; // other error - re-throw error } }.bind(this)) };
Comments
Post a Comment