Javascript的Ajax库支持全球活动全球、Javascript、Ajax

2023-09-10 21:59:15 作者:竟夕起相思

其中 Ajax库我应该用我的阵营/光通量的应用程序?我需要在全球范围内处理错误(如自动注销并重定向到如果401登录;类似$ HTTP的角度服务)。我想用承诺

Which ajax library should I use for my React/Flux app? I need to globally handle errors (e.g. automatically logout and redirect to login if 401; similar to $http service in Angular) and I would like to use promises.

推荐答案

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

The way I'm currently doing it is a combination of three libraries:

Reflux.js 蓝鸟 的jQuery Reflux.js Bluebird 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;

说明:

asyncResult:真正的 createActions 调用创建一个嵌套/异步操作,你可以听。 这里更多 的 listenAndPromise 函数钩子承诺到嵌套完成失败基于结果的回调 The asyncResult: true in the createActions call creates a "nested/asynchronous action" that you can listen to. More Here The listenAndPromise function hooks a promise up to the nested completed and failed callbacks based on the result

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

You can consume the nested actions like this:

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

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

在这个意义上,我们可以通过挂接到所有的 .failed 活动推行全民错误处理程序。

In that sense we can implement a universal error handler by hooking up to all the .failed events.

回流错误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:

To use it in 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);