Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- async function timedgetResponse (expiry = 3500,url) {
- let expired = false;
- async function timeout(expiry){
- await new Promise(_=> setTimeout(_,expiry));
- expired = true;
- return false;
- };
- async function getResponse(url,attempts = 0){
- try {
- if(expired){ return false; };
- const limit = 10;
- if(attempts >= limit){ok: false, e:"MAX_ATTEMPTS"};
- const rawRes = await fetch(url,
- {
- method: 'GET',
- credentials: 'include',
- headers: {
- 'Accept': 'application/json'
- }
- });
- if (!rawRes.ok) { throw (Error('SERVER_ERROR')); };
- const res = await rawRes.json();
- if(!res || res.status === 0){ throw (Error(res.request)); };
- return {ok: true, res: res.request};
- } catch(e){
- const err = e.message;
- if(err === "RESPONSE_NOT_READY"){
- await new Promise(_ => setTimeout(_, 333));
- attempts +=1;
- return getResponse(url,attempts);
- } else
- if(err === "SERVER_ERROR_ON_RESOLVER"){
- await new Promise(_ => setTimeout(_, 10000));
- attempts +=1;
- return getResponse(url,attempts);
- } else {
- return {ok: false, e:"MISC_ERROR"};
- };
- };
- };
- const awaited = await Promise.race([
- getResponse(url),
- timeout(expiry)
- ]);
- return awaited;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement