React-Native Fetch使用Promise封装(一)
项目中封装Fetch的方法
1 /** 2 *2017/04/23 dongtao 3 * 基于 fetch 封装的 GET请求 4 * @param url 5 * @param params {} 6 * @param headers 7 * @returns {Promise} 8 */ 9 var HTTPUtil = {}; 10 11 HTTPUtil.get = function(url, params, headers) { 12 if (params) { 13 let paramsArray = []; 14 //encodeURIComponent 15 Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key])) 16 if (url.search(/\?/) === -1) { 17 url += '?' + paramsArray.join('&') 18 } else { 19 url += '&' + paramsArray.join('&') 20 } 21 } 22 return new Promise(function (resolve, reject) { 23 fetch(url, { 24 method: 'GET', 25 headers: headers, 26 }) 27 .then((response) => { 28 if (response.ok) { 29 return response.json(); 30 } else { 31 reject({status:response.status}) 32 } 33 }) 34 .then((response) => { 35 resolve(response); 36 }) 37 .catch((err)=> { 38 reject({status:-1}); 39 }) 40 }) 41 } 42 43 44 /** 45 * 基于 fetch 封装的 POST请求 FormData 表单数据 46 * @param url 47 * @param formData 48 * @param headers 49 * @returns {Promise} 50 */ 51 HTTPUtil.post = function(url, formData, headers) { 52 return new Promise(function (resolve, reject) { 53 fetch(url, { 54 method: 'POST', 55 headers: headers, 56 body:formData, 57 }) 58 .then((response) => { 59 if (response.ok) { 60 return response.json(); 61 } else { 62 reject({status:response.status}) 63 } 64 }) 65 .then((response) => { 66 resolve(response); 67 }) 68 .catch((err)=> { 69 reject({status:-1}); 70 }) 71 }) 72 }
使用
1 let formData = new FormData(); 2 formData.append("id",1060); 3 4 HTTPUtil.post(url,formData,headers).then((json) => { 5 //处理 请求success 6 if(json.code === 0 ){ 7 //我们假设业务定义code为0时,数据正常 8 }else{ 9 //处理自定义异常 10 this.doException(json); 11 } 12 },(json)=>{ 13 //TODO 处理请求fail