在响应res.readyToShow ===真之前,我如何每秒钟进行一次提取请求。如果res.status为真,则停止请求。
我希望每秒钟发送一个请求,以验证readyToShow是否为真。我不能使用套接字或网络钩子。
test = (ossUrn, md5Checksum) => setTimeout (() => {
fetch(
`google/isReadyToShow`,{
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
urn: ossUrn,
md5Checksum: md5Checksum,
}),
})
.then((response) => {
response.json().then((res) => {
console.log('response ', res);
return (res.readyToShow) ? 0 : this.test(ossUrn, md5Checksum);
});
})
.catch((err) => {
console.log('err ', err);
});
} , 2.5 * 1000);return fetch(
`google/translation`,
{
headers: {
'X-ACCESS-TOKEN-APP' : accessTokenApp,
'X-DRIVE-ID': e.itemData.id,
'X-FILE-NAME': e.itemData.name,
'X-FILE-TYPE': e.itemData.mimeType,
'X-FILE-MD5': e.itemData.md5Checksum,
},
}
)
.then((response) => {
console.log("google item of id clicked " + e.itemData.id);
response.json().then((res) => {
console.log('response ', res);
md5Checksum = e.itemData.md5Checksum;
ossUrn = res.urn;
console.log('URN ', ossUrn)
console.log('URL', res);
console.log('MD5', md5Checksum);
// execute the function to check if the file is ready to be shown
this.test(ossUrn, md5Checksum);
})
.catch((err) => {
console.log(err);
});
}).catch(() => { throw new Error('Data Loading Error'); });
}我尝试使用这段代码,但是我有一个错误:
TypeError: Cannot read properties of undefined (reading 'test')发布于 2022-09-02 12:57:35
您可以将setInterval与一个变量或状态一起使用,该变量或状态确定间隔是否应该继续,或者如果您应该调用clearInterval,因为您已经得到了所需的结果。类似于:
function myIntervalFunction() {
fetch(/*your fetch code*/).then(res => {
if(res.readyToShow) {
// setState, or change a let variable to true
}
})
}
const myInterval = setInterval(myIntervalFunction, 1000) // executes every 1s
// if you're doing it inside a component use state, if outside use a let that starts with false
if(myState || myLetVar === true) { // got what you wanted
clearInterval(myInterval) // stops interval
}https://stackoverflow.com/questions/73582722
复制相似问题