标签:class 网络请求 set 网络 方法 lse eject 结束 res
一、实现思路
//先定义延时函数 const delay = (timeOut = 8*1000) =>{ return new Promise((resolve,reject) =>{ setTimeout(() =>{ reject(new Error(‘网络超时‘); },timeOut); }) } //fetch网络请求 const fetchPromise = (method,url, formData) =>{ return new Promise((resolve, reject) => { fetch(url,{ method: method, body:formData }).then((response) => { if (response.ok) { return response.json(); } else { reject(new Error(‘服务器异常‘)); } }).then((responseJson) => { resolve (responseJson); }).catch((err) => { reject(new Error(err); }) }) } //race任务 const _fetch = (fetchPromise, timeout) => { return Promise.race([fetchPromise,delay(timeout)]); } //post const HttpPost = (url, formData,timeout = 8*1000) =>{ return _fetch(fetchPromise(‘POST‘, url, formData), timeout); }; //get const HttpGet = (url,timeout = 8*1000) =>{ return _fetch(fetchPromise(‘Get‘, url), timeout); };
export {HttpPost ,HttpGet}
参考:
https://www.jianshu.com/p/2df7c6e3b3c3
本博客地址: wukong1688
本文原文地址:https://www.cnblogs.com/wukong1688/p/10963004.html
转载请著名出处!谢谢~~
标签:class 网络请求 set 网络 方法 lse eject 结束 res
原文地址:https://www.cnblogs.com/wukong1688/p/10963004.html