I want to use XMLHttpRequest to receive a JSON file from an API. Currently I need to make to REST call (XMLHttpRequest). Then, use the both responses to create a chart using chart.js.
My only problem is asynchronous problem, and I don't know how to avoid it.
I read a lot of topics but I didn't find the solution.
I made a Promise as the following link: How do I promisify native XHR?
May you help me please?
The code below is the code in the main function (as you can see the tab[0] will be empty) :
let tab = []; // make empty table to save the two results in
/*Request to the API */
for (let counterGraphic = 0; counterGraphic < 2; counterGraphic++) {
let action = 'GET';
let requestURL = 'http://127.0.0.1:5000/' + counterGraphic + '/'; // sample : http://127.0.0.1:5000/0/
makeRequest(action, requestURL, tab)
.then(function(datums) {
console.log(datums);
})
.catch(function(err) {
console.error('Augh, there was an error!', err.statusText);
});
}
let first_tab = tab[0];
console.log(tab[0]);
The code bellow is the function makeRequest :
function makeRequest(method, url, tab) {
return new Promise(function(resolve, reject) {
let xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.responseType = 'json'; //expected format
xhr.onload = function() {
if (this.status >= 200 && this.status < 300) {
let responseRequest = xhr.response; // response to the REST call
let responseRequestString = JSON.stringify(responseRequest) // put it inside ' '
let javascriptArray = JSON.parse(responseRequestString); // parsing of the array
console.log(javascriptArray[0])
tab.push(javascriptArray);
resolve(xhr.response);
} else {
reject({
status: this.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function() {
reject({
status: this.status,
statusText: xhr.statusText
});
};
xhr.send();
});
}