Skip to content

Instantly share code, notes, and snippets.

@th0r
Last active August 29, 2015 14:14
Show Gist options
  • Save th0r/0573ebe44a78fb1ad5a4 to your computer and use it in GitHub Desktop.
Save th0r/0573ebe44a78fb1ad5a4 to your computer and use it in GitHub Desktop.
Fluxible plugin that allows to use promise-style actions
var Bluebird = require('bluebird');
module.exports = function promisifyPlugin(options) {
options = options || {};
/**
* Makes promisified `executeAction` method
*
* @param {Object} actionContext
* @returns {Function}
*/
function makePromisifiedExecuteAction(actionContext) {
return function promisifiedExecuteAction(action, payload, done) {
var promise;
if (action.length === 3) {
// Action uses "done"-callback style
promise = Bluebird.fromNode(cb => action(actionContext, payload, cb));
} else {
// Action uses promises
promise = Bluebird.try(action, [actionContext, payload]);
}
return promise.nodeify(done);
}
}
/**
* @class PromisifyPlugin
*/
return {
name: 'PromisifyPlugin',
plugContext: function plugContext() {
return {
plugActionContext: function plugActionContext(actionContext) {
actionContext.executeAction = makePromisifiedExecuteAction(actionContext);
},
plugComponentContext: function plugComponentContext(componentContext, fluxContext) {
componentContext.executeAction = makePromisifiedExecuteAction(fluxContext.getActionContext());
}
};
}
};
};
@mridgway
Copy link

Usage from gitter:

var updateTime = require('./updateTime');

module.exports = function updateTimeWithAlert(context, payload) {
    return context
        .executeAction(updateTime, payload)
        .then(() => alert('Time updated!'));
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment