react native fetch 简单封装

使用 Promise.race(),进行超时判断的处理

关于 Promise.all() 与 Promise.race()

前者都把每个 Promise 返回的结果都给返回出来,后者返回先执行的 

export default class HttpUtil {
  /**
   * 
   * @param {*} url     请求的 url 地址
   * @param {*} params  请求的参数
   */
  static get(url,params) {
    if(params) {
        url += '?' + params;
    }
    let timeOut = new Promise((resolve,reject) => {
      setTimeout(() => {
        let data = {msg:'请求超时'}
        reject(data)
      },10000)
    })
    let getFetch = new Promise((resolve,reject) => {
      fetch(url)
        .then(response => response.json())
        .then(result => {
          resolve(result);
        })
        .catch(err => {
          let data = {
            msg: '请求出错',
            err,
          }
          reject(data)
        })
    })
    return Promise.race([timeOut, getFetch])
      .then(result => {
        return result
      })
  }

  /**
   * 
   * @param {*} url  url 请求的 url 地址
   * @param {*} data params 请求的参数
   * 以 from 形式提交
   */
  static post(url,data) {
    let timeOut = new Promise((resolve,reject) => {
      setTimeout(() => {
        reject('请求超时')
      },10000)
    })
    let postFetch = new Promise((resolve,reject) => {
      fetch(url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: data
      })
        .then((response) => response.json())
        .then((result) => {
          resolve(result);
        })
        .catch((error) => {
          reject(error);
        });
    })
    return Promise.race([timeOut, postFetch])
      .then(result => {
        return result
      })
  }

  /**
   * 
   * @param {*} url  url 请求的 url 地址
   * @param {*} data params 请求的参数
   * 以 json 格式提交
   */
  static postJson(url,data) {
    let timeOut = new Promise((resolve,reject) => {
      setTimeout(() => {
        reject('请求超时')
      },10000)
    })
    let postFetch = new Promise((resolve,reject) => {
      fetch(url, {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data)
      })
        .then((response) => response.json())
        .then((result) => {
          resolve(result);
        })
        .catch((error) => {
          reject(error);
        });
    })
    return Promise.race([timeOut, postFetch])
      .then(result => {
        return result
      })
  }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值