bixente57 bixente57 - 2 months ago 10
Ajax Question

Unexpected token '>' on ajax promise

My code make an ajax call and manage promises on the ajax function:

element.on("keypress", ".keyEvents", function(event) {
if (event.which == 13) {
// form the url and the json object
var putUrl = url.replace(idInUrl, originElement.attr(idAttr)); //replace idInUrl in url by id
var putObj = {};
putObj[jsonAttr] = $(this).val();

// AJAX query as a promise
console.log(putUrl);
return putAjax(putUrl, putObj).then(data => {
// DOM operation on success
}, error => {
// DOM operation on error
});

} else if (event.which == 27) {
// if Esc is pressed

// replace whith origin element
$(this).replaceWith(originElement);

};
});


The ajax function is defined in the module:

function putAjax(putUrl, putObj) {
return $.ajax({
method: "PUT",
url: putUrl,
data: JSON.stringify(putObj),
contentType: "application/json; charset=utf-8",
});
};


But I have an exception:
Unexpected token '>'
on the line where
return putAjax(...).then
call.

Any idea?

Answer

You mentioned in your comment that you're using Safari 9.1.3.

This does not support arrow functions, so the browser is seeing the = and is expecting an expression on the right hand side. > is not an expression, so it's throwing the error.

You can fix the error by using a ES6 transpiler such as Babel, or by using the older function style:

// ES6 style
(x) => x * 2;

// equivalent old style
function(x) { return x * 2; }

In your code:

element.on("keypress", ".keyEvents", function(event) {
    if (event.which == 13) {
        // form the url and the json object                
        var putUrl = url.replace(idInUrl, originElement.attr(idAttr)); //replace idInUrl in url by id                
        var putObj = {};
        putObj[jsonAttr] = $(this).val();

         // AJAX query as a promise
        console.log(putUrl);
        return putAjax(putUrl, putObj).then(function(data) {
            // DOM operation on success
        },
        function (error) {
            // DOM operation on error
        });

    } else if (event.which == 27) {
        // if Esc is pressed

        // replace whith origin element
        $(this).replaceWith(originElement);

    };
});