Sunday, May 19, 2024
92
rated 0 times [  94] [ 2]  / answers: 1 / hits: 22093  / 8 Years ago, sun, october 23, 2016, 12:00:00

I'm writing webpage with a javascript to read data files in text format from the server per user request. Once the text file has been loaded, I need to manipulate the data somewhat.



I have been using XMLHttpRequest for the loading, however, now I see that synchronous requests are deprecated. I can't start manipulating the data before it's loaded, so what can I do in this case?


More From » xmlhttprequest

 Answers
36

Use an asynchronous request (or fetch, see below, which is also asynchronous):



function doGET(path, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// The request is done; did it work?
if (xhr.status == 200) {
// ***Yes, use `xhr.responseText` here***
callback(xhr.responseText);
} else {
// ***No, tell the callback the call failed***
callback(null);
}
}
};
xhr.open(GET, path);
xhr.send();
}

function handleFileData(fileData) {
if (!fileData) {
// Show error
return;
}
// Use the file data
}

// Do the request
doGET(/path/to/file, handleFileData);


Or using promises, which are the more modern way to handle callbacks (but keep reading):



function doGET(path, callback) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// The request is done; did it work?
if (xhr.status == 200) {
// Yes, use `xhr.responseText` to resolve the promise
resolve(xhr.responseText);
} else {
// No, reject the promise
reject(xhr);
}
}
};
xhr.open(GET, path);
xhr.send();
});
}

// Do the request
doGET(/path/to/file)
.then(function(fileData) {
// Use the file data
})
.catch(function(xhr) {
// The call failed, look at `xhr` for details
});


Here in 2019, there's no reason to use XHR wrapped in a promise like that, just use fetch:



function doGET(url) {
return fetch(url).then(response => {
if (!response.ok) {
throw new Error(HTTP error + response.status); // Rejects the promise
}
});
}

[#60309] Thursday, October 20, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
raveno

Total Points: 453
Total Questions: 92
Total Answers: 92

Location: France
Member since Thu, Oct 27, 2022
2 Years ago
raveno questions
;