Promise Not Resolving As Expected
Solution 1:
If you use return
anywhere inside the httpRequest.onreadystatechange
function, you are not returning a value from ajax
but from the onreadystatechange
event itself.
In cases where you need to wrap callback code with a Promise, you need to use the Promise constructor:
functionajax(file) {
returnnewPromise((resolve, reject) => {
var httpRequest = newXMLHttpRequest();
httpRequest.open('GET', file, true);
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
console.log('success');
console.log(httpRequest.responseText);
resolve(httpRequest.responseText);
} else {
console.log('unexpected 400 error');
reject(0);
}
}
}
httpRequest.send();
});
}
Just for reference, there is a new method called fetch
which already achieves what you are looking for. You can use it as:
promiseDemo(fetch('sample1.html'),fetch('sample2.html')).then(function(sum){
console.log(sum);
},function(){
console.log('Whoopsie!!!!!');
});
A polyfill for browsers is available on GitHub.
Solution 2:
The problem here is that the ajax
function returns undefined
, instead of a Promise which should be resolved/rejected by the onreadystatuschange
function. I think this should work for you...
functionajax(file){
returnnewPromise(function (resolve, reject) {
var httpRequest=newXMLHttpRequest();
httpRequest.open('GET', file, true);
httpRequest.onreadystatechange = function(){
if(httpRequest.readyState == 4){
if(httpRequest.status == 200){
console.log('success');
console.log(httpRequest.responseText);
resolve(httpRequest.responseText);
}
else {
reject({status: httpRequest.status});
return0;
}
}
}
httpRequest.send();
}
}
Solution 3:
I believe your ajax
function does not return a promise, so the promiseDemo
is not getting any promise values to resolve. Try checking what gets passed into the promiseDemo
function.
If that's the problem, you can fix it by creating a new promise in the ajax
function that is returned immediately, and resolved in the http request callback function.
Post a Comment for "Promise Not Resolving As Expected"