0

I've written the script below. It's used to communicate with a backend service. The problem arises when I call the 'heartbeat' method. The problem is probably caused by JavaScript being asynchronous.

I've used the 'done' promise, so the request should be done before I return true or false. As of now the 'heartbeat' is just undefined when evaluated.

/**
 * 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;
                }
            });
        }
    }

})();

I'm doing the following to call the method:

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

heartbeat
'undefined'

What is the reason to the 'heartbeat' variable being undefined? Is it because of the asynchronous way JavaScript works, and is there maybe a way to solve this?

1 Answers1

0

The heartbeat function doesn't have a return statement. (One of the things it does is create a function using a function expression, and that function expression has a return statement, which might be the source of confusion).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • So because 'heartbeat' is already returned by 'Backend' - it's not possible to do a second return statement inside the 'heartbeat' function? – Christoffer Oct 22 '14 at 12:34
  • @Christoffer — No. You can add a return statement to the heartbeat function, you just haven't. (Note that `req.done` is asynchronous, so you can't return `status` because it wouldn't have a value in time). – Quentin Oct 22 '14 at 12:39