Javascript 在这种情况下如何使用Promise JS?
我有:Javascript 在这种情况下如何使用Promise JS?,javascript,node.js,promise,Javascript,Node.js,Promise,我有: function loadDoc123() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("demo").innerHTML = this.responseText;
function loadDoc123() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET","demo_get2.asp?fname=Henry&lname=Ford", true);
xhttp.send();
}
我想实现此代码的promiseJS,但不想编辑代码。我该怎么办?如果不进行编辑,您就不能。您需要将代码包装到承诺中
function loadDoc123() {
return new Promise((res, rej) => {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
res(this.responseText);
}
};
xhttp.open("GET","demo_get2.asp?fname=Henry&lname=Ford", true);
xhttp.send();
});
}
和使用
loadDoc123().then(text => document.getElementById("demo").innerHTML = text);