728x90
반응형
async function doAjaxThings() {
// await code here
let result = await makeRequest("GET", url);
// code below here will only execute when await makeRequest() finished loading
console.log(result);
}
document.addEventListener("DOMContentLoaded", function () {
doAjaxThings();
// create and manipulate your DOM here. doAjaxThings() will run asynchronously and not block your DOM rendering
document.createElement("...");
document.getElementById("...").addEventListener(...);
});
function makeRequest(method, url) {
return new Promise(function (resolve, reject) {
let xhr = new XMLHttpRequest();
xhr.open(method, url);
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
resolve(xhr.response);
} else {
reject({
status: this.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function () {
reject({
status: this.status,
statusText: xhr.statusText
});
};
xhr.send();
});
}
In JavaScript how do I/should I use async/await with XMLHttpRequest?
Full disclosure: I'd qualify myself as having intermediate JavaScript knowledge. So this is slightly above my experience level at this time. I've got a Google Chrome Extension that does an AJAX re...
stackoverflow.com
728x90
반응형
'공부 (@Deprecated)' 카테고리의 다른 글
| [JavaScript] remove tags (0) | 2021.11.29 |
|---|---|
| [Linux] download wget `url` (0) | 2021.11.28 |
| [NewAutoReplyBot-Helper] API (0) | 2021.11.28 |
| [Java] HashMap initialize directly (0) | 2021.11.28 |
| [Java] String[] strings = list.toArray(String[]::new); (0) | 2021.11.27 |