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

设计一个请求中断器,如果请求超过一定的时间未响应就将其中断并返回失败。 #31

Open
CodeRookie262 opened this issue Jan 27, 2021 · 1 comment

Comments

@CodeRookie262
Copy link
Owner

No description provided.

@CodeRookie262 CodeRookie262 changed the title 设计一个请求中断器,如果一个请求在超过一定的时间下未响应就中段并且并且返回失败。 设计一个请求中断器,如果请求超过一定的时间未响应就将其中断并返回失败。 Jan 27, 2021
@CodeRookie262 CodeRookie262 reopened this Jan 27, 2021
@CodeRookie262
Copy link
Owner Author

可以借助 PromiseAbortController 进行异步管控和中断请求。

      function request(options = {}) {
        let { delay, url, option = {} } = options;

        const abortController = new AbortController();
        const signal = abortController.signal;

        return new Promise((resolve, reject) => {
          fetch(url, { ...option, signal })
            .then(r => r.json())
            .then(resolve, reject);

          if (delay === undefined) return;
          const timer = setTimeout(() => {
            abortController.abort();
            reject({ msg: '请求延时' });
            clearTimeout(timer);
          }, delay);
        });
      }

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

No branches or pull requests

1 participant