ReactNative fetch请求封装实现请求超时

以前觉得写这些东西没啥用,现在觉得这是一种很好的知识积累(PS:如果能帮助到别人就更好了,哈哈)。所以决定把之前写的记录下来。

利用Promise.race()实现请求超时

//封装的请求  带超时
const _timeout = 30*1000  //默认30//GET请求
function GET(url, version, timeout = _timeout) {
  var dispatchTimeout = null;
  var timeoutPromise =  new Promise((resolve, reject) => {
    dispatchTimeout = () => {
      reject('请求超时')
    }
  })
  setTimeout(() => {
    dispatchTimeout();
  }, timeout);

  var getPromise = new Promise((resolve, reject) => {
    fetch(url, {
        method: 'GET',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'api-version': version,
        },
    })
    .then((response) => response.json())
    .then((responseData) => {
      resolve(responseData)
    })
    .catch((error) => {
      reject(error);
    })
  })
  return Promise.race([getPromise,timeoutPromise]);
}
//POST请求
function POST(url, version, body, timeout = _timeout) {

  var dispatchTimeout = null;
  var timeoutPromise =  new Promise((resolve, reject) => {
    dispatchTimeout = () => {
      reject('请求超时')
    }
  })
  setTimeout(() => {
    dispatchTimeout();
  }, timeout);

  var postPromise = new Promise((resolve, reject) => {
    fetch(url, {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'api-version': version,
        },
        body: JSON.stringify(body),
    })
    .then((response) => response.json())
    .then((responseData) => {
      resolve(responseData)
    })
    .catch((error) => {
      reject(error)
    });
  })

  return Promise.race([postPromise,timeoutPromise]);
}

export { GET, POST }

使用方法:

import { GET, POST } from './XXXXX'

var body = {
'name':'zhang',
'age': '25',
}
var url = 'https://www.baidu.com/'
var timeout = 10*1000 //这个参数可以不要 有默认超时时间
POST(url,'1.0.0',body,timeout)
      .then((responseData) => {
    console.log(responseData);
      })
      .catch((error) => {
        console.log(error);//超时和错误会在这里
      })

你可能感兴趣的:(ReactNtive)