fetch函数没有默认超时时间的配置吗
最佳答案 问答题库558位专家为你答疑解惑
chatgpt:
https://chat.xutongbao.top/
截至我知识的最后更新时间(2023年),原生的 fetch
API 在大多数浏览器中并没有内置的默认超时时间。这意味着如果你没有明确地设置一个超时期限,fetch
请求可能会永远挂起(或者直到浏览器决定停止尝试为止)。
如果你需要设置超时,你可以自己实现一个超时机制。以下是一个在JavaScript中使用 fetch
API 时设置超时的例子:
const fetchWithTimeout = (resource, options = {}) => {const { timeout = 8000 } = options; // 设置默认超时时间为8000msconst 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。如果在超时时间内没有收到响应,AbortController
的 abort
方法会被调用,这会导致 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').valuedocument.getElementById('input').value = ''const fetchWithTimeout = (resource, options = {}) => {const { timeout = 8000 } = options // 设置默认超时时间为8000msconst 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) returnconst reader = response.body.getReader()// 创建了一个文本解码器const decoder = new TextDecoder()let count = 0reader.read().then(function processText({ done, value }) {if (done) {messageHot += '【结束】'document.getElementById('result').innerHTML = messageHotreturn}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 += textdocument.getElementById('result').innerHTML = messageHotcount++console.log('次数', count, text)}return reader.read().then(processText)})}</script></body>
</html>
参考链接:
https://chat.xutongbao.top/
https://blog.csdn.net/xutongbao/article/details/134337330?spm=1001.2014.3001.5501
99%的人还看了
相似问题
猜你感兴趣
版权申明
本文"fetch函数没有默认超时时间的配置吗":http://eshow365.cn/6-38269-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!
- 上一篇: 如何提升管理组织能力?
- 下一篇: 国际阿里云:Windows实例中数据恢复教程!!!