Promise returning undefined

后端 未结 4 1682
醉话见心
醉话见心 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 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);
    

提交回复
热议问题