// 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. windows下cmd清屏命令cls

    windows下cmd清屏命令cls

  2. linux装sqlite3

    下载sqlite3源码包 tar xvfz sqlite-src-3.3.5 cd sqlite-3.3.5 ./configure –no-tcl make python继续一次. apt inst ...

  3. Java学习笔记之Linux下的Java安装和配置

    0x00 概述 由于使用 yum 或者 apt-get 命令 安装 openjdk 可能存在类库不全,从而导致用户在安装后运行相关工具时可能报错的问题,所以此处我们推荐采用手动解压安装的方式来安装 J ...

  4. flask模板,路由,消息提示,异常处理

    1.flask的路由与反向路由 from flask import Flask, request, url_for app = Flask(__name__) @app.route('/') def ...

  5. win7搭建pyqt4开发环境

    版本 win7 64bit python2.7 https://www.python.org/ftp/python/2.7.13/python-2.7.13.amd64.msi pyqt4 https ...

  6. paymob浙江正和

    #region 上海 ZH //else if (order.SP.Contains("上海") && order.Area.Contains("移动&q ...

  7. Codeforces Round #424 (Div. 2, rated, based on VK Cup Finals) Problem C (Codeforces 831C) - 暴力 - 二分法

    Polycarp watched TV-show where k jury members one by one rated a participant by adding him a certain ...

  8. mtr 命令

    mtr命令的使用: -r  --report  以报告的方式发布监测的结果 -s 30   指定发送包的大小  这个随意   按照自己的需求 -i 10  设置icmp协议返回包的时间 -n  no- ...

  9. 经典算法分析:n^2与nlgn

    冒泡.插入.选择排序的时间复杂度为O(n2) Arrays.sort()时间复杂度为nlgn 具体算法实现代码: package recursion; import java.util.Arrays; ...

  10. Spring Boot 项目中常见注解

    @Autowired 自动导入依赖的 Bean.byType方式.把配置好的 Bean拿来用,完成属性.方法的组装,它可以对类成员变量.方法及构造函数进行标注,完成自动装配的工作 import org ...