// 1: 传统fetch操作
fetch('http://facebook.github.io/react-native/movies.json')
.then((response) => response.json())
.then((responseJson) => {
return responseJson.movies;
//操作
})
.catch((error) => {
console.error(error);
}); // 2:使用promise封装fetch ,异步执行
let common_url = 'http://192.168.1.1:8080/'; //服务器地址
let token = '';
/**
* @param {string} url 接口地址
* @param {string} method 请求方法:GET、POST,只能大写
* @param {JSON} [params=''] body的请求参数,默认为空
* @return 返回Promise
*/
function fetchRequest(url, method, params = ''){
let header = {
"Content-Type": "application/json;charset=UTF-8",
"accesstoken":token //用户登陆后返回的token,某些涉及用户数据的接口需要在header中加上token
};
console.log('request url:',url,params); //打印请求参数
if(params == ''){ //如果网络请求中带有参数
return new Promise(function (resolve, reject) {
fetch(common_url + url, {
method: method,
headers: header
}).then((response) => response.json())
.then((responseData) => {
console.log('res:',url,responseData); //网络请求成功返回的数据
resolve(responseData);
})
.catch( (err) => {
console.log('err:',url, err); //网络请求失败返回的数据
reject(err);
});
});
}else{ //如果网络请求中没有参数
return new Promise(function (resolve, reject) {
fetch(common_url + url, {
method: method,
headers: header,
body:JSON.stringify(params) //body参数,通常需要转换成字符串后服务器才能解析
}).then((response) => response.json())
.then((responseData) => {
console.log('res:',url, responseData); //网络请求成功返回的数据
resolve(responseData);
})
.catch( (err) => {
console.log('err:',url, err); //网络请求失败返回的数据
reject(err);
});
});
}
}
// 然后我们去使用这个封装请求函数GET
fetchRequest('app/book','GET')
.then( res=>{
//请求成功
if(res.header.statusCode == 'success'){
//这里设定服务器返回的header中statusCode为success时数据返回成功
}else{
//服务器返回异常,设定服务器返回的异常信息保存在 header.msgArray[0].desc
console.log(res.header.msgArray[].desc);
}
}).catch( err=>{
//请求失败
})
//Post
let params = {
username:'admin',
password:''
}
fetchRequest('app/signin','POST',params)
.then( res=>{
//请求成功
if(res.header.statusCode == 'success'){
//这里设定服务器返回的header中statusCode为success时数据返回成功 }else{
//服务器返回异常,设定服务器返回的异常信息保存在 header.msgArray[0].desc
console.log(res.header.msgArray[].desc);
}
}).catch( err=>{
//请求失败
}) // 3:加入超时处理,跟上面没关系
/**
* 让fetch也可以timeout
* timeout不是请求连接超时的含义,它表示请求的response时间,包括请求的连接、服务器处理及服务器响应回来的时间
* fetch的timeout即使超时发生了,本次请求也不会被abort丢弃掉,它在后台仍然会发送到服务器端,只是本次请求的响应内容被丢弃而已
* @param {Promise} fetch_promise fetch请求返回的Promise
* @param {number} [timeout=10000] 单位:毫秒,这里设置默认超时时间为10秒
* @return 返回Promise
*/
function timeout_fetch(fetch_promise,timeout = ) {
let timeout_fn = null; //这是一个可以被reject的promise
let timeout_promise = new Promise(function(resolve, reject) {
//超时函数
timeout_fn = function() {
reject('timeout promise');
};
}); //这里使用Promise.race,以最快 resolve 或 reject 的结果来传入后续绑定的回调,
//先执行fetch_promise 等待数据的返回,如果在定时后还没返回 就执行超时函数
let abortable_promise = Promise.race([
fetch_promise,
timeout_promise
]); setTimeout(function() {
timeout_fn();
}, timeout); return abortable_promise ;
} //应用:加入超时处理的fetchRequest网络请求的使用方法跟没加入超时处理一样。
let common_url = 'http://192.168.1.1:8080/'; //服务器地址
let token = '';
/**
* @param {string} url 接口地址
* @param {string} method 请求方法:GET、POST,只能大写
* @param {JSON} [params=''] body的请求参数,默认为空
* @return 返回Promise
*/
function fetchRequest(url, method, params = ''){
let header = {
"Content-Type": "application/json;charset=UTF-8",
"accesstoken":token //用户登陆后返回的token,某些涉及用户数据的接口需要在header中加上token
};
console.log('request url:',url,params); //打印请求参数
if(params !== ''){ //如果网络请求中带有参数
return new Promise(function (resolve, reject) {
timeout_fetch(fetch(common_url + url, {
method: method,
headers: header
})).then((response) => response.json())
.then((responseData) => {
console.log('res:',url,responseData); //网络请求成功返回的数据
resolve(responseData);
})
.catch( (err) => {
console.log('err:',url, err); //网络请求失败返回的数据
reject(err);
});
});
}else{ //如果网络请求中没有参数
return new Promise(function (resolve, reject) {
timeout_fetch(fetch(common_url + url, {
method: method,
headers: header,
body:JSON.stringify(params) //body参数,通常需要转换成字符串后服务器才能解析
})).then((response) => response.json())
.then((responseData) => {
console.log('res:',url, responseData); //网络请求成功返回的数据
resolve(responseData);
})
.catch( (err) => {
console.log('err:',url, err); //网络请求失败返回的数据
reject(err);
});
});
}
}
//参考文章http://imweb.io/topic/57c6ea35808fd2fb204eef63

封装fetch的使用(包含超时处理)的更多相关文章

  1. 封装fetch请求失败和超时再次请求

    转: 封装fetch请求失败和超时再次请求 function _fetch(fetch_promise, timeout) { var abort_fn = null; //这是一个可以被reject ...

  2. React Native 网络请求封装:使用Promise封装fetch请求

    最近公司使用React作为前端框架,使用了异步请求访问,这里做下总结: React Native中虽然也内置了XMLHttpRequest 网络请求API(也就是俗称的ajax),但XMLHttpRe ...

  3. Fetch方法封装、业务实践

    说Fetch之前啊,我们不得不说一说Ajax了,以前使用最多的自然是jQuery封装的Ajax方法了,强大而且好用. 有人说了,jQuery的Ajax都已经封装得那么好了,你还整Fetch干什么,这不 ...

  4. angular访问后台服务及监控会话超时的封装

    angular访问后台服务及监控会话超时的封装 angular本身自带访问组件http和httpclient,组件本身都是异步模式访问.本文只列举了对http组件的封装同时也一同处理会话超时监控. 获 ...

  5. 封装及调用fetch

    一.封装fetch 创建fetch/index.js import 'whatwg-fetch' import 'es6-promise' export function get(url) { let ...

  6. react-native fetch 请求封装

    1.fetch 函数封装 fetch.js /** * 请求头 * @type {{Accept: string, Content-Type: string}} */ const header = { ...

  7. ES6 fetch方法封装

    // 请求路径 let url = 'http://jsonplaceholder.typicode.com/users' // 传输数据参数 const dataName = { name: &qu ...

  8. ES6 promise 封装http请求

    今天研究了一下同事封装的http请求,用的是promise. 大结构是: const __fetch = (url, data = {}, config = {}) => { let param ...

  9. fetch使用的常见问题及解决办法

    首先声明一下,本文不是要讲解fetch的具体用法,不清楚的可以参考MDN fetch教程. 引言 说道fetch就不得不提XMLHttpRequest了,XHR在发送web请求时需要开发者配置相关请求 ...

随机推荐

  1. centos 安装MySQL全过程

    1.到chinaunix下载mysql 下载地址: http://download.chinaunix.net/download/0008000/7159.shtml 2.上传到CentOS服务器 本 ...

  2. SQL Server char,varchar,nchar,nvarchar区别

    SQL Server char,varchar,nchar,nvarchar区别 (1)       定义: char:    固定长度,存储ANSI字符,不足的补英文半角空格. nchar:   固 ...

  3. prufer编码 cayley定理

    背景(在codeforces 917D 报废后,看题解时听闻了这两个玩意儿.实际上917D与之“木有关西”,也可以认为是利用了prufer的一些思路.) 一棵标号树的Pufer编码规则如下:找到标号最 ...

  4. DOS下读取smbios的汇编程序(通过搜索memory)

    汇编程序编写的读取smbios的代码: ;------------------------------------------------- ;功能: 读取SMBIOS 的Entry Point ,并 ...

  5. 微信企业号OAuth2.0验证接口来获取成员的身份信息

    <?php $appid = "请输入您企业的appid"; $secret = "请输入您企业的secreat"; if (!isset($_GET[' ...

  6. Tsung压力测试工具安装使用

    工具安装 1)unixODBC ./configure; make; make install 或者yum安装 2)ncurses-devel ./configure; make; make inst ...

  7. linux交换区使用过多导致的性能问题

    近日,我们开发发现有一台配置相同的服务器跑的特别慢,相同数据量的情况下,其他服务器只要跑10分钟,这台服务器要跑50分钟,经确认,所有的应用层配置参数都相同.上去之后,发现该服务器swap使用比较多, ...

  8. Python 使用 face_recognition 人脸识别

    Python 使用 face_recognition 人脸识别 官方说明:https://face-recognition.readthedocs.io/en/latest/readme.html 人 ...

  9. linux homebrew skill 技巧

    $ cat /usr/bin/gitdiffH0#!/bin/bashgit diff HEAD $(git ls-files| grep '\.py$\|\.py\.in$') | osflake8 ...

  10. python简说(二十六)异常

    # try:# res = 1 / 0# except ZeroDivisionError as e:# print('出错啦,除数不能为0',e) # l = list()# l.append(1) ...