假设有多个设备连接在后端,数量不定,需要按个读回状态,那么就要在循环里fetch了.
此函数非常好用,来自于国内一个作者,时间久了,忘记了来源,抱歉.
export default async function fetchWithTimeout(resource, options = {}) {
const { timeout = 1000 } = options;
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeout);
const response = await fetch(resource, {
...options,
signal: controller.signal,
});
clearTimeout(id);
return response;
}
使用:
try {
for (let i = 0; i < autowindownum.length; i++) {
const sth = await getAutoWindow(
serverAddress,
storeInfo.devicenum,
autowindownum[i],
storeInfo.deviceip
);
console.log(sth.result);
setAutoWindow((old) => [
...old,
{
num: autowindownum[i],
img: getAutoWindowImage(sth.result[9]),
statu: getAutoWindowStatu(sth.result[9]),
},
]);
}
} catch (error) {
console.log("error-----------", error);
}
export async function getAutoWindow(serverAddress, devicenum, channelNum, deviceip) {
//console.log(serverAddress, devicenum, channelNum, deviceip);
const options = {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
timeout: 3000,
};
const res = await fetchWithTimeout(
`${serverAddress}/api/v1/measure/autowindow?devicenum=${devicenum}&&channelnum=${channelNum}&&deviceip=${deviceip}`,
options
);
const data = await res.json();
// console.log(data);
return data;
}