aboutsummaryrefslogtreecommitdiff
path: root/app/static/polltask.js
diff options
context:
space:
mode:
authorrubenwardy <rw@rubenwardy.com>2018-05-11 15:29:26 +0100
committerrubenwardy <rw@rubenwardy.com>2018-05-11 15:29:26 +0100
commit510bf50ff2fb29817fc754d6793e506e3414bc6b (patch)
treed4dc5c04d9bcf793593d7091607b978c1950832a /app/static/polltask.js
parent6d7b810270b21575dca54eb36f371969b976bafd (diff)
downloadcheatdb-510bf50ff2fb29817fc754d6793e506e3414bc6b.tar.xz
Remove meta refresh on task page, use JS to poll
Diffstat (limited to 'app/static/polltask.js')
-rw-r--r--app/static/polltask.js56
1 files changed, 56 insertions, 0 deletions
diff --git a/app/static/polltask.js b/app/static/polltask.js
new file mode 100644
index 0000000..bc9d802
--- /dev/null
+++ b/app/static/polltask.js
@@ -0,0 +1,56 @@
+function getJSON(url, method) {
+ return new Promise(function(resolve, reject) {
+ fetch(new Request(url, {
+ method: method || "get",
+ credentials: "same-origin",
+ headers: {
+ "Accept": "application/json",
+ },
+ })).then(function(response) {
+ response.text().then(function(txt) {
+ resolve(JSON.parse(txt))
+ }).catch(reject)
+ }).catch(reject)
+ })
+}
+
+function pollTask(poll_url, disableTimeout) {
+ return new Promise(function(resolve, reject) {
+ var tries = 0;
+ function retry() {
+ tries++;
+ if (!disableTimeout && tries > 10) {
+ reject("timeout")
+ } else {
+ const interval = Math.min(tries*100, 1000)
+ console.log("Polling task in " + interval + "ms")
+ setTimeout(step, interval)
+ }
+ }
+ function step() {
+ getJSON(poll_url).then(function(res) {
+ if (res.status == "SUCCESS") {
+ console.log("Got result")
+ resolve(res.result)
+ } else {
+ retry()
+ }
+ }).catch(retry)
+ }
+ retry()
+ })
+}
+
+
+function performTask(url) {
+ return new Promise(function(resolve, reject) {
+ getJSON(url, "post").then(function(startResult) {
+ console.log(startResult)
+ if (typeof startResult.poll_url == "string") {
+ pollTask(startResult.poll_url).then(resolve).catch(reject)
+ } else {
+ reject("Start task didn't return string!")
+ }
+ }).catch(reject)
+ })
+}