Promise Returning Undefined
I am trying to use promise to send an ajax request to a php script which checks if a file exist on the server and returns a boolean value. I have the below code but the fileExists
Solution 1:
Try this:
functionfileExists(url) {
return promise = newPromise(function(resolve, reject) {
var xhr = newXMLHttpRequest();
xhr.onload = function() {
resolve(this.responseText);
};
xhr.onerror = reject;
xhr.open('GET', url);
xhr.send();
});
}
fileExists("url_to_file").then(text =>console.log(text));
Your function returns nothing. If you return the promise you can hold on to the data once it's resolved.
Solution 2:
This part of your code:
promise.then(function(e) {
return e;
});
only returns e
to the callback function. You have to handle the result within that callback.
promise.then(function() {
// handle result;
});
Or might as well return the promise as shown by @Ole.
Solution 3:
You should return the promise, because you need to assign your result variable asynchronous.
functionfileExists(url) {
returnnewPromise(function(resolve, reject) {
var xhr = newXMLHttpRequest();
xhr.onload = function() {
resolve(this.responseText);
};
xhr.onerror = reject;
xhr.open('GET', url);
xhr.send();
});
}
fileExists("url_to_file").then(console.log);
Solution 4:
Your function must return a Promise
.
functionfileExists(url) {
returnnewPromise(function (resolve, reject) {
var xhr = newXMLHttpRequest();
xhr.onload = function() {
resolve(this.responseText);
};
xhr.onerror = reject();
xhr.open('GET', url);
xhr.send();
});
}
Then just call the function and print the resolved text
fileExists("url_to_file").then(function (text) {
console.log(text);
});
Post a Comment for "Promise Returning Undefined"