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

编程入门 行业动态 更新时间:2024-10-25 09:38:27

fetch<a href=https://www.elefans.com/category/jswz/34/1771370.html style=函数没有默认超时时间的配置吗"/>

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

 chatgpt:

/

截至我知识的最后更新时间(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('', { 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').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('', { 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(`/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>

参考链接:

/

=1001.2014.3001.5501

更多推荐

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

本文发布于:2023-11-15 05:28:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1594477.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   时间   fetch

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!