Created
May 9, 2021 16:02
-
-
Save ayanchoudhary/5164d7ee460af6cb52e6cdf1fb8400a8 to your computer and use it in GitHub Desktop.
polling function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// XHR helper function | |
function xhrRequest(url, method) { | |
return new Promise((resolve, reject) => { | |
const req = new XMLHttpRequest(); | |
req.timeout = 6000; | |
req.onload = () => { | |
if (req.status === 200) { | |
try { | |
resolve(req.response); | |
} catch (err) { | |
reject(`Couldn't parse response. ${err.message}, ${req.response}`); | |
} | |
} else { | |
reject(`Request had an error: ${req.status}`); | |
} | |
} | |
req.ontimeout = () => { | |
console.log("polling..") | |
resolve(xhrRequest(url, method)) | |
} | |
req.onerror = (err) => { | |
console.log(err) | |
reject(err) | |
} | |
req.open(method, url, true); | |
req.responseType = 'json'; | |
req.send(); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment