jQuery和couchdb:是否有可能在一个处理程序中处理“已创建”和“已存在”?

时间:2013-05-04 11:27:28

标签: jquery ajax rest couchdb

典型的模式没有使用REST couchDB API是“如果不存在则创建”。例如,如果我想创建一个不存在的数据库:

$.ajax({
  type: 'PUT',
  url: DB + 'mydatabase',
});

作为程序员,201 Created412 Prerequisite failed都是成功的,因为我希望数据库到位,如果它刚刚创建或者它已经存在,那对我来说完全没问题。但是从jQuery的角度来看,201是成功的,412是失败的 - 所以我需要编写大量代码才能确保数据库到位:

$.ajax({
  type: 'PUT',
  url: DB + 'mydatabase',
}).fail( function( arg ) {
  if( 412 == arg.statusCode ) {
    // This is success.
  } else {
    //  This is failure.
  }
}).done( function( arg ) {
  //  This is another success.
});

这有效地使代码在两个地方成功混乱(甚至在两个不同的回调中!)。是否有可能以较少的代码减少错误处理,最好是在一个地方处理成功?

1 个答案:

答案 0 :(得分:5)

或者,您可以使用statusCode对象将共享事件处理程序绑定到 200 412

$.ajax({
    type: 'PUT',
    url: DB + 'mydatabase',
    statusCode: {
        200: myHandler,
        412: myHandler
    }
});

function myHandler(data, statusText, jqXHR) {
    // do something with the data
}

为了完整性,这是我在评论中描述的另一种方式。

$.ajax({
    type: 'PUT',
    url: DB + 'mydatabase',
    complete: function(jqXHR) {
        if (jqXHR.status === 200 || jqXHR.status === 412) {
            // do something
        }
        return;
    }
});