Javascript的Ajax库支持全球活动

Javascript的Ajax库支持全球活动

本文介绍了Javascript的Ajax库支持全球活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

其中 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:

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

说明:

  • 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);

这篇关于Javascript的Ajax库支持全球活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 20:17