javascriptjqueryrequirejsrsvp.jsrsvp-promise

Uncaught ReferenceError: RSVP is not defined , error while using require.js with rsvp


I am working on a demo showing the error handling in promises using rsvp.js. Everything seemed fine, till I used the CDN url for rsvp.js in a tag. Now since I have require.js for module loading in my application, I tried loading the rsvp.js module via require js syntax. In the Chrome network tab, I see the rsvp.js module getting loaded properly as well, but I get the below error in console,

Uncaught ReferenceError: RSVP is not defined.

require(["bootstrap","js/rsvp"], function(bootstrap,rsvp) { 
$(document).ready(function () {
    function getEmployeeDetails() {
        var radioValue1 = $("input[name='option1']:checked").val();
        var requrl;
        if (radioValue1 == "fail") {
            requrl = "../../../testservice/getEmployeeIdss";
        } else {
            requrl = "../../../testservice/getEmployeeId";
        }
        return new RSVP.Promise(function (resolve, reject) {
            $.ajax({
                url: requrl,
                success: function (response) {
                    try {
                        $('#successBoard').append("<b> <i> Ajax Call 1 Succeeded! </i>  </b><br/>" + "Employee ID:" + response.stuId + "<br/>");
                        resolve(response.stuId);
                    } catch (e) {
                        reject(e);
                    }
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    console.log('Ajax 1 failed : Rejecting Promise 1');
                    $('#errorBoard').append("<b> <i> Ajax 1 failed : Rejecting Promise 1</i>  </b><br/>");
                    reject(thrownError);
                }
            });

        });
    }

Solution

  • I took a look at the source code of RSVP and found this code:

    /* global define:true module:true window: true */
    if (typeof define === 'function' && define['amd']) {
      define(function() { return RSVP; });
    } else if (typeof module !== 'undefined' && module['exports']) {
      module['exports'] = RSVP;
    } else if (typeof platform !== 'undefined') {
      platform['RSVP'] = RSVP;
    }
    

    The first if is where RSVP detects that it is running in an AMD environment and registers as an AMD module. So you won't have a global RSVP.

    Now, in your code you require RSVP and bind it to the rsvp variable, all lowercase. So it is accessible as rsvp, not RSVP. Either refer to it as rsvp or change the variable name in the function you pass to require so that it is RSVP:

    require(["bootstrap", "js/rsvp"], function (bootstrap, RSVP) { 
    

    Note that there's no point in having a reference to Bootstrap because it installs itself as a jQuery plugin, so you could do:

    require(["js/rsvp", "bootstrap"], function (RSVP) {