Skip to content

Instantly share code, notes, and snippets.

@ayanchoudhary
Created May 9, 2021 16:02
Show Gist options
  • Save ayanchoudhary/5164d7ee460af6cb52e6cdf1fb8400a8 to your computer and use it in GitHub Desktop.
Save ayanchoudhary/5164d7ee460af6cb52e6cdf1fb8400a8 to your computer and use it in GitHub Desktop.
polling function
// 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