fetch设置请求超时

常规封装 fetch

// 封装fetch
let POST = function(url, params) {
  const URLS = baseURL + url;
  return fetch(URLS, {
    method: "POST",
    // body: params,
    body: params,
    headers: {
      Accept: "application/json",
      "Content-Type": "application/x-www-form-urlencoded",
      // "Content-Type": "application/json",
      // token: JSON.parse(sessionStorage.getItem("token"))
    },
    mode: "cors", // 以CORS的形式跨域
    cache: "force-cache"
  })
    .then(data => {
      return data.json();
    })
    .then(ret => {
      if (ret.code != 0) {
        return { code: ret.code, msg: ret.message };
      } else {
        return ret;
      }
    });
};

单独设置超时

 // 请求超时
function advertisement(data) {
 return Promise.race([
   // 常规封装 fetch
   fetch.POST('URL', data),
   new Promise((resovle,reject) => {setTimeout(() => {
     reject(new Error('请求超时'));
   },30000)})
 ])
 .then(res => {
   return res.data; // 请求成功
 }).catch(err => {
   console.log(err) // 请求超时
 })
}

封装设置超时

let POST = function(url, params) {
  const URLS = baseURL + url;
  return Promise.race([
  fetch(URLS, {
    method: "POST",
    // body: params,
    body: params,
    headers: {
      Accept: "application/json",
      "Content-Type": "application/x-www-form-urlencoded",
      // "Content-Type": "application/json",
      // token: JSON.parse(sessionStorage.getItem("token"))
    },
    mode: "cors", // 以CORS的形式跨域
    cache: "force-cache"
  })
    new Promise((resovle,reject) => {setTimeout(() => {
      reject(new Error('请求超时'));
    },10000)})
  ])
  .then(res => {  // 请求成功
    if (ret.code != 0) {
      return { code: ret.code, msg: ret.message };
    } else {
      return ret;
    }
  }).catch(err => { // 请求超时
    console.log(err)
  })
};

你可能感兴趣的:(javascript,前端,vue.js,fetch,js)