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 function always return undefined.
How can I wrap the promise in a function and have the function return the promise value?
function fileExists(url) {
var promise = new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
resolve(this.responseText);
};
xhr.onerror = reject;
xhr.open('GET', url);
xhr.send();
});
promise.then(function(e) {
return e;
});
}
var result = fileExists("url_to_file");
Promise can be resolved with undefined but not reflected in type · Issue #11094 · microsoft/TypeScript · GitHub.
Returns a new Promise object that is resolved with the given value. If the value is a thenable (i.e. has a then method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise, the returned promise will be fulfilled with the value.
resolve() method "resolves" a given value to a Promise . If the value is a promise, that promise is returned; if the value is a thenable, Promise. resolve() will call the then() method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value.
The new Promise() constructor returns a promise object. As the executor function needs to handle async operations, the returned promise object should be capable of informing when the execution has been started, completed (resolved) or retuned with error (rejected).
Try this:
function fileExists(url) {
return promise = new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With