关于javascript:axios源码七

7次阅读

共计 1760 个字符,预计需要花费 5 分钟才能阅读完成。

今日来看发送申请的 dispatchRequest.
dispatchRequest 就是一个函数, 承受 config 做参数, 外围是应用 adapter(config 中的属性) 办法发送申请, 而后将返回的数据进行转换. 因为是 promise, 所以胜利返回 response, 失败返回 reject 谬误

'use strict';

var utils = require('./../utils');
var transformData = require('./transformData');
var isCancel = require('../cancel/isCancel');
var defaults = require('../defaults');

/**
 * Throws a `Cancel` if cancellation has been requested.
 * 
 * 抛出一个 Cancel 如果一个 cancellation 曾经被申请
 */
function throwIfCancellationRequested(config) {if (config.cancelToken) {config.cancelToken.throwIfRequested();
  }
}

/**
 * Dispatch a request to the server using the configured adapter.
 * 
 * 应用配置的适配器给服务器散发一个申请
 *
 * @param {object} config The config that is to be used for the request   申请的配置
 * @returns {Promise} The Promise to be fulfilled  返回实现的 Promise
 */
module.exports = function dispatchRequest(config) {throwIfCancellationRequested(config);

  // Ensure headers exist   确保头部存在
  config.headers = config.headers || {};

  // Transform request data   转化申请数据
  config.data = transformData(
    config.data,
    config.headers,
    config.transformRequest
  );

  // Flatten headers  使头部扁平化
  config.headers = utils.merge(config.headers.common || {},
    config.headers[config.method] || {},
    config.headers
  );

  utils.forEach(['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
    function cleanHeaderConfig(method) {delete config.headers[method];
    }
  );

  var adapter = config.adapter || defaults.adapter;

  return adapter(config).then(function onAdapterResolution(response) {throwIfCancellationRequested(config);

    // Transform response data
    response.data = transformData(
      response.data,
      response.headers,
      config.transformResponse
    );

    return response;
  }, function onAdapterRejection(reason) {if (!isCancel(reason)) {throwIfCancellationRequested(config);

      // Transform response data
      if (reason && reason.response) {
        reason.response.data = transformData(
          reason.response.data,
          reason.response.headers,
          config.transformResponse
        );
      }
    }

    return Promise.reject(reason);
  });
};
正文完
 0