After sending an HTTP request I check if the status
is 200, then resolve()
, but the if
statement doesn't seem to work.
function getMelumat() {
let promise = new Promise((resolve,reject)=>{
let xhr = new XMLHttpRequest();
xhr.open("GET",'https://jsonplaceholder.typicode.com/posts');
xhr.send()
xhr.onload = ()=>{
if ( this.status == 200){
resolve(this.response)
}
else {
throw "AN ERROR OCCURED"
}
}
})
return promise
}
getMelumat().then(data=>{
return JSON.parse(data)
}).then(data=>{
console.log(data)
})
Checking if the status is 200 is not enough; you also need to check this.readyState
.
The headers (with the status) will already be available at this.readyState == 2
, but the whole response won't be complete until this.readyState == 4
.