diff --git a/static/focus.js b/static/focus.js index 4b43735..b73c671 100644 --- a/static/focus.js +++ b/static/focus.js @@ -5,39 +5,48 @@ const API = { buhForms: "/api3/buh", }; -function run() { - sendRequest(API.organizationList, (orgOgrns) => { +async function run() { + try { + const orgOgrns = await sendRequest(API.organizationList); const ogrns = orgOgrns.join(","); - sendRequest(`${API.orgReqs}?ogrn=${ogrns}`, (requisites) => { - const orgsMap = reqsToMap(requisites); - sendRequest(`${API.analytics}?ogrn=${ogrns}`, (analytics) => { - addInOrgsMap(orgsMap, analytics, "analytics"); - sendRequest(`${API.buhForms}?ogrn=${ogrns}`, (buh) => { - addInOrgsMap(orgsMap, buh, "buhForms"); - render(orgsMap, orgOgrns); - }); - }); - }); - }); -} -run(); + const [requisites, analytics, buh] = await Promise.all([ + sendRequest(`${API.orgReqs}?ogrn=${ogrns}`), + sendRequest(`${API.analytics}?ogrn=${ogrns}`), + sendRequest(`${API.buhForms}?ogrn=${ogrns}`) + ]); + + const orgsMap = reqsToMap(requisites); + addInOrgsMap(orgsMap, analytics, "analytics"); + addInOrgsMap(orgsMap, buh, "buhForms"); + render(orgsMap, orgOgrns); + } catch (error) { + console.error(error); + } +} -function sendRequest(url, callback) { - const xhr = new XMLHttpRequest(); - xhr.open("GET", url, true); - xhr.onreadystatechange = function () { - if (xhr.readyState === XMLHttpRequest.DONE) { - if (xhr.status === 200) { - callback(JSON.parse(xhr.response)); - } - } - }; +run(); - xhr.send(); +function sendRequest(url) { + return new Promise((resolve, reject) => { + fetch(url) + .then(response => { + if (!response.ok) { + alert(`Request failed with status ${response.status} ${response.statusText}`); + } + return response.json(); + }) + .then(data => { + resolve(data); + }) + .catch(error => { + reject(error); + }); + }) } + function reqsToMap(requisites) { return requisites.reduce((acc, item) => { acc[item.ogrn] = item;