fetch函数没有默认超时时间的配置吗
  KvevbRuwqC1X 2023年12月11日 18 0


截至我知识的最后更新时间(2023年),原生的 fetch API 在大多数浏览器中并没有内置的默认超时时间。这意味着如果你没有明确地设置一个超时期限,fetch 请求可能会永远挂起(或者直到浏览器决定停止尝试为止)。

如果你需要设置超时,你可以自己实现一个超时机制。以下是一个在JavaScript中使用 fetch API 时设置超时的例子:

const fetchWithTimeout = (resource, options = {}) => {
  const { timeout = 8000 } = options; // 设置默认超时时间为8000ms

  const controller = new AbortController();
  const id = setTimeout(() => controller.abort(), timeout);

  const response = fetch(resource, {
    ...options,
    signal: controller.signal
  }).then((response) => {
    clearTimeout(id);
    return response;
  }).catch((error) => {
    clearTimeout(id);
    throw error;
  });

  return response;
};

// 使用这个函数进行fetch请求并设置超时
fetchWithTimeout('https://your-api-endpoint.com', { timeout: 5000 }) // 设置5秒的超时
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Request timed out or another error: ', error));

在这个例子中,我们创建了一个名为 fetchWithTimeout 的新函数,它接受一个资源URL和一个选项对象。该函数使用了AbortController,这是一个可让你通过调用其 abort 方法终止一个网络请求的API。如果在超时时间内没有收到响应,AbortControllerabort 方法会被调用,这会导致 fetch 请求被取消。请注意,AbortController 是较新的 API,尽管得到了良好的浏览器支持,但在使用之前仍然值得检查目标用户的浏览器。

值得注意的是,服务器端的 fetch 实现(如在Node.js环境中使用的 node-fetch)可能会有不同的行为或配置选项,因此如果你在服务器环境中工作,你应该查阅相应库的文档以确定如何设置超时。

chatgpt stream模式请求超时设置:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <textarea id="input"></textarea>
    <div>
      <button onclick="handleSend()">发送</button>
    </div>
    <div id="result"></div>
    <script>
      async function handleSend() {
        let messageHot = ''
        document.getElementById('result').innerHTML = ''

        let content = document.getElementById('input').value
        document.getElementById('input').value = ''

        const fetchWithTimeout = (resource, options = {}) => {
          const { timeout = 8000 } = options // 设置默认超时时间为8000ms

          const controller = new AbortController()
          const id = setTimeout(() => controller.abort(), timeout)

          const response = fetch(resource, {
            ...options,
            signal: controller.signal,
          })
            .then((response) => {
              clearTimeout(id)
              return response
            })
            .catch((error) => {
              clearTimeout(id)
              throw error
            })

          return response
        }

        // 使用这个函数进行fetch请求并设置超时
        // fetchWithTimeout('https://your-api-endpoint.com', { timeout: 5000 }) // 设置5秒的超时
        //   .then((response) => response.json())
        //   .then((data) => console.log(data))
        //   .catch((error) =>
        //     console.error('Request timed out or another error: ', error)
        //   )

        const response = await fetchWithTimeout(
          `https://chat.xutongbao.top/api/light/chat/createChatCompletion`,
          {
            timeout: 30 * 60 * 1000,
            method: 'post',
            headers: {
              'Content-Type': 'application/json',
              Accept: 'text/event-stream',
            },
            body: JSON.stringify({
              model: 'gpt-3.5-turbo-1106',
              token: 'sk-3d76d415-dd72-43ff-b7c8-65fb426f1d7b',
              messages: [
                {
                  role: 'user',
                  content,
                },
              ],
              params: {
                n: 1,
                stream: true,
              },
            }),
          }
        )

        if (!response.body) return

        const reader = response.body.getReader()
        // 创建了一个文本解码器
        const decoder = new TextDecoder()

        let count = 0
        reader.read().then(function processText({ done, value }) {
          if (done) {
            messageHot += '【结束】'
            document.getElementById('result').innerHTML = messageHot
            return
          }
          let text = decoder.decode(value)
          if (text) {
            if (
              text.length > 9 &&
              text.slice(text.length - 9) === 'undefined'
            ) {
              text = text.slice(0, text.length - 9)
            }
            let start852Index = text.indexOf('start852')
            let end852Index = text.indexOf('end852')

            if (start852Index >= 0 && end852Index >= 0) {
              let headerData = text.slice(start852Index + 8, end852Index)
              console.log('headerData', headerData)
              text = text.slice(end852Index + 6)
            }

            messageHot += text
            document.getElementById('result').innerHTML = messageHot
            count++
            console.log('次数', count, text)
          }

          return reader.read().then(processText)
        })
      }
    </script>
  </body>
</html>

fetch函数没有默认超时时间的配置吗_json

fetch函数没有默认超时时间的配置吗_前端_02


【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年12月11日 0

暂无评论

推荐阅读
KvevbRuwqC1X