我想检查一个对象是否存在于REST集合中,一旦成功,我想将一个finalObject变量设置为该对象的名称来创建它,失败时意味着原始对象不存在,我想要将变量设置为该对象的变量以创建它,但如果该对象不存在,我将获得404并且程序停止执行。什么是实现这一目标的最佳方式?
我的代码如下所示:
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();
}
答案 0 :(得分:1)
我认为这是因为你没有回复正确的承诺:
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;
}
<强>更新强>
$.ajax()
是一项承诺,因此您可以删除.promise()
:
function _getObjectByName(objectName) {
var url = ''; //construct REST URL;
return $.ajax({ ... }); // <<
}