Skip to content

Commit

Permalink
Improve call stack usage in SequentialExecutor.callListeners()
Browse files Browse the repository at this point in the history
Converts recursive loop to sequential one for synchronous listeners.
  • Loading branch information
lsegal committed Oct 20, 2014
1 parent f38b4c8 commit 1478892
Showing 1 changed file with 19 additions and 17 deletions.
36 changes: 19 additions & 17 deletions lib/sequential_executor.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,29 +84,31 @@ AWS.SequentialExecutor = AWS.util.inherit({
* @api private
*/
callListeners: function callListeners(listeners, args, doneCallback) {
if (listeners.length === 0) {
doneCallback.call(this);
return;
var self = this;
function callNextListener(err) {
if (err) {
doneCallback.call(self, err);
} else {
self.callListeners(listeners, args, doneCallback);
}
}

var self = this, listener = listeners.shift();
if (listener._isAsync) { // asynchronous listener
var callNextListener = function(err) {
if (err) {
while (listeners.length > 0) {
var listener = listeners.shift();
if (listener._isAsync) { // asynchronous listener
listener.apply(self, args.concat([callNextListener]));
return; // stop here, callNextListener will continue
} else { // synchronous listener
try {
listener.apply(self, args);
} catch (err) {
doneCallback.call(self, err);
} else {
self.callListeners(listeners, args, doneCallback);
return;
}
};
listener.apply(self, args.concat([callNextListener]));
} else { // synchronous listener
try {
listener.apply(self, args);
self.callListeners(listeners, args, doneCallback);
} catch (err) {
doneCallback.call(self, err);
}
}

doneCallback.call(self);
},

/**
Expand Down

0 comments on commit 1478892

Please sign in to comment.