Advertisement
Guest User

Untitled

a guest
Jul 20th, 2019
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.25 KB | None | 0 0
  1. async function timedgetResponse (expiry = 3500,url) {
  2. let expired = false;
  3. async function timeout(expiry){
  4. await new Promise(_=> setTimeout(_,expiry));
  5. expired = true;
  6. return false;
  7. };
  8.  
  9. async function getResponse(url,attempts = 0){
  10. try {
  11. if(expired){ return false; };
  12. const limit = 10;
  13. if(attempts >= limit){ok: false, e:"MAX_ATTEMPTS"};
  14. const rawRes = await fetch(url,
  15. {
  16. method: 'GET',
  17. credentials: 'include',
  18. headers: {
  19. 'Accept': 'application/json'
  20. }
  21. });
  22. if (!rawRes.ok) { throw (Error('SERVER_ERROR')); };
  23. const res = await rawRes.json();
  24. if(!res || res.status === 0){ throw (Error(res.request)); };
  25. return {ok: true, res: res.request};
  26. } catch(e){
  27. const err = e.message;
  28. if(err === "RESPONSE_NOT_READY"){
  29. await new Promise(_ => setTimeout(_, 333));
  30. attempts +=1;
  31. return getResponse(url,attempts);
  32. } else
  33. if(err === "SERVER_ERROR_ON_RESOLVER"){
  34. await new Promise(_ => setTimeout(_, 10000));
  35. attempts +=1;
  36. return getResponse(url,attempts);
  37. } else {
  38. return {ok: false, e:"MISC_ERROR"};
  39. };
  40.  
  41. };
  42. };
  43.  
  44. const awaited = await Promise.race([
  45. getResponse(url),
  46. timeout(expiry)
  47. ]);
  48.  
  49. return awaited;
  50. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement