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

AbortSignal.timeout() #53

Open
hax opened this issue Nov 8, 2023 · 1 comment
Open

AbortSignal.timeout() #53

hax opened this issue Nov 8, 2023 · 1 comment

Comments

@hax
Copy link
Owner

hax commented Nov 8, 2023

常见的给请求加 timeout 的代码:

async function get(url: string, timeout: number) {
  const timeoutPromise = new Promise((_, reject) => {
    setTimeout(() => reject(new Error("Timeout")), timeout);
  })
  const fetchPromise = fetch(url)
  // 使用Promise.race来竞赛fetch请求和超时Promise
  return Promise.race([fetchPromise, timeoutPromise])
}

这代码work,但利用好API可以更简单:

  return fetch(url, { signal: AbortSignal.timeout(timeout) })
@hax
Copy link
Owner Author

hax commented Nov 8, 2023

Off topic:有些IDE有显示 parameter name 的选项,但在这个例子里感觉有点唠叨:

AbortSignal.timeout(time:timeout)

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