2015-04-25 24 views

回答

1

目前我在做它的方式是三个库的组合:

  1. Reflux.js
  2. Bluebird
  3. jQuery的

webutils.js

var Promise = require('bluebird'); 

module.exports = { 
    makeApiCall: function() { 
    return Promise.resolve($.get("http://makeyourapicall")); 
    } 
}; 

actions.js:

var Reflux = require('reflux'); 
var WebUtils = require('web-utils.js'); 

var Actions = Reflux.createActions({ 
    getDataFromServer: { asyncResult: true } 
}); 

Actions.getDataFromServer.listenAndPromise(WebUtils.makeApiCall); 

module.exports = Actions; 

说明:

  • createActions调用的asyncResult: true创建一个 “嵌套/异步操作”,你可以听。 More Here
  • listenAndPromise功能挂钩基于结果的承诺,到嵌套completedfailed回调

可以消耗嵌套操作是这样的:

Actions.getDataFromServer.complete.listen(res => console.log('success', res)); 

Actions.getDataFromServer.failed.listen(err => console.log('failed', err)); 

在这个意义上,我们可以实现通过连接所有的.failed事件来处理通用的错误处理程序。

回流错误handler.js

var _ = require('lodash'); 
var Reflux = require('reflux'); 
var NotificationStore = require('../stores/NotificationStore'); 

/** 
* Overall error handler for async actions 
* @param err 
*/ 
function handleError(err) { 
    console.error('Encountered error:', err); 
    NotificationStore.createErrorNotification(err); 
} 

/** 
* Loops over refluxActions and attaches an error handler to all async actions 
* @param refluxActions {Object} hash of the reflux actions ot generate 
* @constructor 
*/ 
var RefluxErrorHandler = function(refluxActions) { 
    _.forEach(refluxActions, func => { 
    if(func.failed) { 
     func.failed.listen(handleError); 
    } 
    }); 
    return refluxActions; 
}; 

module.exports.wrapRefluxActions = RefluxErrorHandler; 

要actions.js使用它:

var Reflux = require('reflux'); 
var WebUtils = require('web-utils.js'); 
var RefluxErrorHandler = require('reflux-error-handler.js'); 

var Actions = Reflux.createActions({ 
    getDataFromServer: { asyncResult: true } 
}); 

Actions.getDataFromServer.listenAndPromise(WebUtils.makeApiCall); 

module.exports = RefluxErrorHandler(Actions);