gpt4 book ai didi

reactjs - 如何使用 react js 在 Fetch API 中设置超时

转载 作者:行者123 更新时间:2023-12-04 11:36:52 25 4
gpt4 key购买 nike

我在 react js 中使用 fetch post 方法,当向后端发送请求时,需要 7 分钟才能提供响应,并且在前端自动超时之前。你能帮我解决如何在 fetch 方法中设置 10 mints 时间让前端等待响应,只有当后端需要超过 10 mints 时才会超时。
如果我必须安装任何依赖项,请告诉我们。

也只是为了通知您我已经安装了依赖项“whatwg-fetch-timeout”:“^2.0.2-timeout”并且它在开发服务器上运行良好
但是当尝试创建构建包时,它无法创建构建构建。
示例代码:

fetch("http://" + hostName + ":" + port + "/searchData", {
method: "POST",
headers: {
"Content-Type": "application/json",
Login: login,
ID: id
},
body: JSON.stringify({
StartDate: StartDate === "" ? null : StartDate,
EndDate: EndDate === "" ? null : EndDate,
FileName: FileName === "" ? null : FileName,
RecordCount: RecordCount === "" ? null : RecordCount,
Status: Status
})
})
.then(response => {
resStatus = response.status;
return response.json();
})
.then(responseJson => {
//source code
})
.catch(error => {});

最佳答案

如何添加自己的超时
就像是

function timeoutPromise(ms, promise) {
return new Promise((resolve, reject) => {
const timeoutId = setTimeout(() => {
reject(new Error("promise timeout"))
}, ms);
promise.then(
(res) => {
clearTimeout(timeoutId);
resolve(res);
},
(err) => {
clearTimeout(timeoutId);
reject(err);
}
);
})
}

然后在 ES7 async/await 语法中调用它
async request() {
try {
let res = await timeoutPromise(10*60*1000, fetch('/hello'));
} catch(error) {
// might be a timeout error
}
}

也适用于引用 Fetch API request timeout?尝试这个。

关于reactjs - 如何使用 react js 在 Fetch API 中设置超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55086659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com