Promise returning undefined

后端 未结 4 1663
醉话见心
醉话见心 2020-12-21 09:39

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

相关标签:
4条回答
  • 2020-12-21 09:57
    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();
    }); 
    }
    
    var result = fileExists("url_to_file").then(foo());
    

    Try this.

    your function returns nothing . If you return the promise you can hold on to the data once its resolved.

    0 讨论(0)
  • 2020-12-21 10:03

    You should return the promise, because you need to assign your result variable asynchronous.

    function fileExists(url) {
      return 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(console.log);
    
    0 讨论(0)
  • 2020-12-21 10:04

    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.

    0 讨论(0)
  • 2020-12-21 10:06

    Your function must return a Promise.

    function fileExists(url) {
        return new Promise(function (resolve, reject) {
            var xhr = new XMLHttpRequest();
            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);
    });
    
    0 讨论(0)
提交回复
热议问题