Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fetch 封装 #16

Open
3 tasks done
rccoder opened this issue May 11, 2017 · 2 comments
Open
3 tasks done

Fetch 封装 #16

rccoder opened this issue May 11, 2017 · 2 comments

Comments

@rccoder
Copy link
Member

rccoder commented May 11, 2017

原生:

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

  • 返回 Promise
  • 超时处理
  • 做成网路请求基础库
@rccoder
Copy link
Member Author

rccoder commented May 11, 2017

让fetch也可以timeout

@rccoder
Copy link
Member Author

rccoder commented May 11, 2017

最后封装:

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant