Skip to content
New issue

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

fetchUtil.js #8

Open
mqy1023 opened this issue Dec 16, 2016 · 0 comments
Open

fetchUtil.js #8

mqy1023 opened this issue Dec 16, 2016 · 0 comments

Comments

@mqy1023
Copy link
Owner

mqy1023 commented Dec 16, 2016

const defaultHeader = {
  'Accept': 'application/json',
  'Content-Type': 'application/json'
};

const delayPromise = (delay) => { // 默认3秒后没返回数据就是超时
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      reject({ status: 408, msg: '网络连接超时!' });
    }, delay);
  });
};

const fetchPromise = (url) => {
  return new Promise((resolve, reject) => {
    fetch(url)
    .then((response) => response.json())
    .then((res) => {
      console.log('res, res', res);
      resolve(res);
    }).catch(err => {
      console.log('err, err', err);
      reject(err);
    })
    .done();
  });
}

const fetchData = (url, delay = 3000) => {
  return Promise.race([delayPromise(delay), fetchPromise(url)]);
}

export default fetchData;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant