xhr helpers: wrap in promises

This commit is contained in:
Andrew Dolgov 2018-12-11 08:42:38 +03:00
parent 36f3299ddf
commit 7cfd04ffb4
1 changed files with 24 additions and 12 deletions

View File

@ -18,23 +18,35 @@ function exception_error(e, e_compat, filename, lineno, colno) {
function xhrPost(url, params, complete) { function xhrPost(url, params, complete) {
console.log("xhrPost:", params); console.log("xhrPost:", params);
return new Ajax.Request(url, {
parameters: params, return new Promise((resolve, reject) => {
onComplete: complete new Ajax.Request(url, {
parameters: params,
onComplete: function(reply) {
if (complete != undefined) complete(reply);
resolve(reply);
}
});
}); });
} }
function xhrJson(url, params, complete) { function xhrJson(url, params, complete) {
return xhrPost(url, params, (reply) => { return new Promise((resolve, reject) => {
try { return xhrPost(url, params).then((reply) => {
const obj = JSON.parse(reply.responseText); let obj = null;
complete(obj);
} catch (e) {
console.error("xhrJson", e, reply);
complete(null);
}
}) try {
obj = JSON.parse(reply.responseText);
} catch (e) {
console.error("xhrJson", e, reply);
}
if (complete != undefined) complete(obj);
resolve(obj);
});
});
} }
/* add method to remove element from array */ /* add method to remove element from array */