函数返回undefined用于获取请求

时间:2017-05-01 03:37:44

标签: javascript

我正在尝试定义一个函数来检查文件是否存在,但该函数总是未定义,即使找到该文件:

  var findFile = function(startURL) {
    var host = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '');
    var uri = host + startURL + '/file.js';
    //console.log(uri);
    var http = new XMLHttpRequest();
    http.open('GET',uri,true);
    http.send();   

    var processRequest = function (e) {
      if (http.status == 200) {
        return "found";
      } else {
        console.log(http.status);
        console.log(http.readyState);
        return 'not_found';
      }
    }
    http.onreadystatechange = processRequest;
  }

运行一个有效的文件(从http得到200结果),我得到一个未定义的结果。

a = findFile('/app');
>undefined

我在回报声明中做错了什么?

修改

我添加了回调函数,但我仍然未定义:

这是我现在的代码:

  var findServiceWorkerFile = function(startURL,callback) {
    var host = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '');
    var uri = host + startURL + '/RoasSDKWorker.js';
    //console.log(uri);
    var http = new XMLHttpRequest();
    http.open('GET',uri,true);
    http.send();   
    var file_status;
    var processRequest = function (e) {
      if (http.status == 200) {
        file_status = 'found';
        callback(file_status);
         "found";
      } else {
        file_status = 'not_found';
        callback(file_status);
      }
    }
    http.onreadystatechange = processRequest;

  }

  function findFileCallBack(value) {
    return value;
  }

1 个答案:

答案 0 :(得分:1)

由于undefined,函数findFile已成为异步函数,您将获得XMLHttpRequest()

函数调用a = findFile('/app');将执行网络I / O并立即返回。它不会等待网络请求完成。

您必须使用回调来获取findFile函数的返回值,这是一个标准的javascript范例。你可以做这样的事情

var findFile = function(startURL, callback) {
    var host = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '');
    var uri = host + startURL + '/file.js';
    //console.log(uri);
    var http = new XMLHttpRequest();
    http.open('GET',uri,true);
    http.send();   

    var processRequest = function (e) {
      if (http.status == 200) {
        callback("found");
      } else {
        console.log(http.status);
        console.log(http.readyState);
        callback("not_found");
      }
    }
    http.onreadystatechange = processRequest;
  }

function b(ret_val) {
  console.log(ret_val);
}
findFile('/app', b);

我还没有对代码进行过测试,但这只是一个暗示你可以如何工作的提示。 代码为here

相关问题