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();
}