We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
原生:
fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${ret}`, }, body: JSON.stringify(data), }) .then(res => res.json()) .then(res => { console.log('api 数据返回信息: '); console.log(res); return resolve(res.msg); });
封装下:
返回 Promise,参数调用简化
import urlMap from '@url'; import storage from '@storage'; export function fetchData(data) { return new Promise((resolve, reject) => { storage.load({ key: 'token', }).then(ret => { console.log('请求数据'); console.log({ auth: `Bearer ${ret}`, body: data, }); fetch(urlMap.api, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${ret}`, }, body: JSON.stringify(data), }) .then(res => res.json()) .then(res => { console.log('api 数据返回信息: '); console.log(res); return resolve(res.msg); }); }); }) }
The text was updated successfully, but these errors were encountered:
让fetch也可以timeout
Sorry, something went wrong.
最后封装:
import Storage from './storage'; /** * @desc Promise 处理超时 * @param fetchOkPromise * @param timeout * @returns {Promise.<Object>} */ const handleTimeOut = (fetchOkPromise, timeout) => { let timeOutFn = null; const fetchTimeOutPromise = new Promise((resolve, reject) => { timeOutFn = () => { reject({ msg: 'timeout' }); } }); // 超时调用 timeOutFn reject setTimeout(() => { timeOutFn(); }, timeout); // 优先返回的 return Promise.race([ fetchOkPromise, fetchTimeOutPromise ]); } /** * @desc 拥有超时处理的 fetch,返回 Promise * @param {Object} params fetch所需要的参数 * @param {Number} timeout 超时时间 * @param {bool} debug 是否打开 debug 模式 */ const WeFetch = (params, timeout = 2000, debug = false) => { const { url, method = 'POST', data } = params; const fetchPromise = new Promise((resolve, reject) => { Storage.load('token').then(val => { return fetch (url, { method, headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${val}`, }, body: JSON.stringify(data), }) .then(res => { if (debug) { console.log({ desc: 'API 返回数据', url, res, token: val }) } return res.json(); }) .then(res => { return resolve(res && res.msg); }); }) }); return handleTimeOut(fetchPromise, timeout); } export default WeFetch;
调用
import { WeFetch } from '@base'; import urlMap from '@url'; export function fetchData(data) { return WeFetch({ url: urlMap.api, data }); }
No branches or pull requests
原生:
封装下:
返回 Promise,参数调用简化
TODO
The text was updated successfully, but these errors were encountered: