Ciao a tutti, non riesco a ficcarmi in testa questo oggetto promise.
Tramite 2 funzioni infio una richiesta xmlhttprequest inglobato in promise ecco il codice:
codice:
var xhr = (url, data, pgr) => {
return new Promise(function(resolve, reject) {
let xhttp = new XMLHttpRequest;
xhttp.open("POST", url, true);
xhttp.onreadystatechange = function() {
if (xhttp.readyState === 4 && xhttp.status === 200) {
resolve(xhttp.responseText);
} else {
alert(xhttp.onerror);
reject(xhttp.onerror);
}
}
xhttp.send(data);
if (pgr === 1) {
.........
}
});
}
function prova(){
const bt = document.querySelector("#btSend");
btSend(0, bt, bt.innerText);
formdata = new FormData();
formdata.append("username", username.value);
formdata.append("password", password.value);
xhttp = xhr("/scr/lgn.php", formdata, 0)
.then(function(response) {
alert(response);
if (response !== "") {
document.getElementById("resFrmLgn").innerText = response;
}
btSend(1, bt, "");
}).catch(function(error) {
console.log(error);
btSend(1, bt, "");
});
}
il problema che resolve() mi da sempre null;
mentre se faccio alert(xhttp.responseText) il risultato ce