Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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");
like image 259
K Hsueh Avatar asked Jun 22 '17 06:06

K Hsueh


People also ask

Can a promise be undefined?

Promise can be resolved with undefined but not reflected in type · Issue #11094 · microsoft/TypeScript · GitHub.

What happens when a promise is returned?

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.

Does returning resolve a promise?

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.

Can a promise return an object?

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).


Video Answer


2 Answers

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.

like image 86
Hari Haran Avatar answered Oct 20 '22 19:10

Hari Haran


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.

like image 28
Rax Weber Avatar answered Oct 20 '22 19:10

Rax Weber