Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 发送ajax请求时返回语句出现问题_Javascript_Jquery_Asynchronous - Fatal编程技术网

Javascript 发送ajax请求时返回语句出现问题

Javascript 发送ajax请求时返回语句出现问题,javascript,jquery,asynchronous,Javascript,Jquery,Asynchronous,我已经写了下面的脚本。它用于与后端服务通信。当我调用“heartbeat”方法时,问题就出现了。问题可能是由于JavaScript是异步的 我已经使用了“完成”承诺,所以在我返回true或false之前应该完成请求。到目前为止,“心跳”在计算时还没有定义 /** * This module is used to communicate with the backend. */ var Backend = (function() { /** * Default settin

我已经写了下面的脚本。它用于与后端服务通信。当我调用“heartbeat”方法时,问题就出现了。问题可能是由于JavaScript是异步的

我已经使用了“完成”承诺,所以在我返回true或false之前应该完成请求。到目前为止,“心跳”在计算时还没有定义

/**
 * This module is used to communicate with the backend.
 */
var Backend = (function() {

    /**
     * Default settings for the Backend module.
     * @type {[Object]}
     */
    var settings = {
        api: 'https://www.domain.tld/api'
    };

    /**
     * This is used to create a request against the backend.
     * @param  {[String]} method   The HTTP method to be used.
     * @param  {[String]} endpoint Endpoint to target.
     * @return {[Object]}          Returns the XHR request.
     */
    var request = function(method, endpoint) {
        req = $.ajax({
            url: settings.api + endpoint,
            type: method
        });

        return req;
    };

    return {

        /**
         * Check the backend status.
         * @return {[Bool]} Returns true or false - depending on the status.
         */
        heartbeat: function() {
            var req = request('get', '/heartbeat');

            req.done(function(data) {
                if(data.status == 'alive') {
                    return true;
                } else {
                    return false;
                }
            });
        }
    }

})();
我正在执行以下操作来调用该方法:

var backend = Backend();
var heartbeat = backend.heartbeat();

heartbeat
'undefined'

“heartbeat”变量未定义的原因是什么?这是因为JavaScript的异步工作方式吗?有没有办法解决这个问题?

heartbeat函数没有return语句。它所做的一件事是使用函数表达式创建一个函数,该函数表达式有一个返回语句,这可能是造成混淆的原因。

因此,由于“heartbeat”已经由“Backend”返回,因此不可能在“heartbeat”函数中执行第二个返回语句?@christoff-否。您可以将返回语句添加到heartbeat函数中,但您没有。请注意,req.done是异步的,所以不能返回status,因为它在时间上没有值。