I use async and for loop to test for fetch issues that might be caused by network or other issues. but testing too often It generates a request error similar to endless pings. After returning, I want to wait 3000 milliseconds before restarting the test. This is my code:
const fetchtest = async (url, opts, tries=FETCHTEST_LOOP) => {
const sleep = m => new Promise(r => setTimeout(r, m));
const errs = [];
for (let i = 0; i < tries; i++) {
try {
return await fetch(url, opts).then(sleep(3000)) ; // << When returned, wait 3000 ms to restart the test.
}
catch (err) {
errs.push(err);
}
}
throw errs;
};
this is my log:
𓊈2𓊉 369 update at actiVity
trying GET [1 of 10]
trying GET [2 of 10]
trying GET [2 of 10]
trying GET [1 of 10]
trying GET [2 of 10]
trying GET [1 of 10]
trying GET [2 of 10]
trying GET [4 of 10]
trying GET [3 of 10]
trying GET [2 of 10]
trying GET [1 of 10]
trying GET [3 of 10]
trying GET [1 of 10]
trying GET [2 of 10]
trying GET [1 of 10]
trying GET [2 of 10]
trying GET [4 of 10]
trying GET [3 of 10]
trying GET [1 of 10]
trying GET [2 of 10]
trying GET [2 of 10]
trying GET [2 of 10]
trying GET [1 of 10]
trying GET [3 of 10]
trying GET [2 of 10]
trying GET [1 of 10]
trying GET [4 of 10]
trying GET [2 of 10]
trying GET [1 of 10]
trying GET [2 of 10]
trying GET [1 of 10]
𓊈2𓊉 370 update at actiVity
trying GET [1 of 10]
trying GET [2 of 10]
𓊈2𓊉 370 update at actiVity
𓊈2𓊉 370 update at actiVity
I am new to this.
I got an answer for this. i change to @vercel/fetch API it makes me not need to use setTimeout.
I don't know exactly what you are trying but maybe I can give some idea.
const fetchtest = async (url, opts, tries=FETCHTEST_LOOP) => {
const errs = [];
for (let i = 0; i < tries;) {
try {
const response = await fetch(url, opts);
const data = response.json()
if (data){
setTimeout(()=>{i++},3000)
}
}
catch (err) {
errs.push(err);
setTimeout(()=>{i++},3000)
}
}
throw errs;
};
it is not super elegant but at least it waits 3 seconds before restarting the loop.
Again it is not clear what you exactly want(I mean purpose of your whole task/test) and possibly there is better way to achieve.