【问题标题】:Javascript ajax library supporting global events支持全局事件的 Javascript ajax 库
【发布时间】:2015-04-25 16:12:44
【问题描述】:

我的 React/Flux 应用程序应该使用哪个 ajax 库?我需要全局处理错误(例如,如果 401 自动注销并重定向到登录;类似于 Angular 中的 $http 服务)并且我想使用 Promise。

【问题讨论】:

    标签: javascript ajax events request reactjs


    【解决方案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 事件来实现通用错误处理程序。

    reflux-error-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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多