0

I would like to check if an object exists in a collection with REST, on succeed, I want to set a finalObject variable to that object's name to create it, on fail which means original object doesn't exist, I want to set variable the variable to that object to create it, but if that object doesn't exist I am getting 404 and the program stops executing. what's the best way to achieve this?

My code looks like below:

var finalObjectName;
function _addObject(objectName) {
    var mypromise = _checkIfExists(objectName);
    mypromise.done(function () {
        //Add the object to the collection
    });
}//end function


function _checkIfExists(objectName) {
    var mypromise = _getObjectByName(objectName);
    var dfd = $.Deferred();

    mypromise.then(
        function (data, status, jqXHR) {
            finalObjectName = generateName(); //object exists, then generate another name
        },
        function (jqXHR, status, error) {
            finalObjectName = objectName; //object doesn't exist, use same name
        });

    return dfd.promise();
};

function _getObjectByName(objectName) {
    var url = ''; //construct REST URL;
    return ($.ajax({..}).promise();
}
Shanoor
  • 13,344
  • 2
  • 29
  • 40
Natalie
  • 297
  • 1
  • 3
  • 9
  • 1
    A REST api uses http codes to tell you things. Error 404 stands for "Not found", it's not an error in this case, the api is telling you the object is not found. You have to check the error code and act accordingly (if 404 => object doesn't exist, 401 => unauthorized and so on). More informations here: https://stackoverflow.com/questions/2001773/understanding-rest-verbs-error-codes-and-authentication?rq=1 – Shanoor Dec 23 '15 at 07:16

1 Answers1

1

I think it's because you're not returning the right promise:

function _checkIfExists(objectName) {
    var mypromise = _getObjectByName(objectName);
    // var dfd = $.Deferred(); << not useful

    mypromise.then(
        function (data, status, jqXHR) {
            finalObjectName = generateName(); //object exists, then generate another name
        },
        function (jqXHR, status, error) {
            finalObjectName = objectName; //object doesn't exist, use same name
        });

    // return dfd.promise(); << this is an empty promise
    return mypromise;
}

Update

$.ajax() is a promise so you can remove .promise():

function _getObjectByName(objectName) {
    var url = ''; //construct REST URL;
    return $.ajax({ ... }); // <<
}
Shanoor
  • 13,344
  • 2
  • 29
  • 40