From f0f067391468769fad8f39c86becea49813469af Mon Sep 17 00:00:00 2001 From: Darren Date: Sat, 18 Oct 2014 01:54:48 +0100 Subject: [PATCH] PluginInterface.emit readability --- server/plugininterface.js | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/server/plugininterface.js b/server/plugininterface.js index 322efa6..d74ec6c 100644 --- a/server/plugininterface.js +++ b/server/plugininterface.js @@ -55,18 +55,21 @@ PluginInterface.prototype.off = PluginInterface.prototype.removeListener = funct PluginInterface.prototype.emit = function emit(type, data) { var that = this; + return new Promise(function (emit_resolve, emit_reject) { var rejected = false, - rejected_reasons = []; + rejected_reasons = [], + listeners_promise; if (!that.listeners[type]) { return emit_resolve(data); } - (that.listeners[type].reduce(function (listener_promise, listener) { + // Add each listener as a promise .then() + listeners_promise = that.listeners[type].reduce(function (listener_promise, listener) { return listener_promise.then(function (data) { return new Promise(function (resolve) { - listener({ + var event_data = { callback: function () { resolve(data); }, @@ -76,10 +79,15 @@ PluginInterface.prototype.emit = function emit(type, data) { rejected_reasons.push(reason); } } - }, data); + }; + + listener(event_data, data); }); }); - }, Promise.resolve(data))).then(function (data) { + }, Promise.resolve(data)); + + // After all the listeners have been called, resolve back with any modified data + listeners_promise.then(function (data) { if (rejected) { emit_reject({data: data, reasons: rejected_reasons}); } else { -- 2.25.1