WeHIT / wiki

Small Record In WeHIT Development
0 stars 0 forks source link

Fetch 封装 #16

Open rccoder opened 7 years ago

rccoder commented 7 years ago

原生:

fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${ret}`,
      },
      body: JSON.stringify(data),
})
      .then(res => res.json())
      .then(res => {
        console.log('api 数据返回信息: ');
        console.log(res);
        return resolve(res.msg);
      });

封装下:

返回 Promise,参数调用简化

import urlMap from '@url';
import storage from '@storage';

export function fetchData(data) {
  return new Promise((resolve, reject) => {
    storage.load({
      key: 'token',
    }).then(ret => {
      console.log('请求数据');
      console.log({
        auth: `Bearer ${ret}`,
        body: data,
      });
      fetch(urlMap.api, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${ret}`,
      },
      body: JSON.stringify(data),
      })
      .then(res => res.json())
      .then(res => {
        console.log('api 数据返回信息: ');
        console.log(res);
        return resolve(res.msg);
      });
    });
  })
}

TODO

rccoder commented 7 years ago

让fetch也可以timeout

rccoder commented 7 years ago

最后封装:

import Storage from './storage';

/**
 * @desc Promise 处理超时
 * @param fetchOkPromise
 * @param timeout
 * @returns {Promise.<Object>}
 */
const handleTimeOut = (fetchOkPromise, timeout) => {

  let timeOutFn = null;

  const fetchTimeOutPromise = new Promise((resolve, reject) => {
    timeOutFn = () => {
      reject({
        msg: 'timeout'
      });
    }
  });

  // 超时调用 timeOutFn reject
  setTimeout(() => {
    timeOutFn();
  }, timeout);

  // 优先返回的
  return Promise.race([
    fetchOkPromise,
    fetchTimeOutPromise
  ]);
}

/**
 * @desc 拥有超时处理的 fetch,返回 Promise
 * @param {Object} params fetch所需要的参数
 * @param {Number} timeout 超时时间
 * @param {bool} debug 是否打开 debug 模式
 */
const WeFetch = (params, timeout = 2000, debug = false) => {

  const {
    url,
    method = 'POST',
    data
  } = params;

  const fetchPromise = new Promise((resolve, reject) => {

    Storage.load('token').then(val => {
      return fetch (url, {
        method,
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${val}`,
        },
        body: JSON.stringify(data),
      })
        .then(res => {
          if (debug) {
            console.log({
              desc: 'API 返回数据',
              url,
              res,
              token: val
            })
          }
          return res.json();
        })
        .then(res => {
          return resolve(res && res.msg);
        });
    })

  });

  return handleTimeOut(fetchPromise, timeout);
}

export default WeFetch;

调用

import { WeFetch } from '@base';

import urlMap from '@url';

export function fetchData(data) {
  return WeFetch({
    url: urlMap.api,
    data
  });
}