在jQuery的Promise对象中扩展done()

doq*_*que 0 javascript ajax jquery promise jquery-deferred

我想包装$.ajax().done()一个单独的类,其中包括针对模式验证JSON响应.

示例调用可能如下所示:

myService.get("/api/people").done(function(people) {
    // at this point I'm certain the data in people is valid
    template.render(people);
}).catch(function() {
    // this happens if validation of people failed, even if the request itself was successfull
    console.log("empty json or validation failed");
});
Run Code Online (Sandbox Code Playgroud)

成功回调函数是传入的done(),但是只应在私有函数中执行(_validate(data, schema))返回true).不太优雅的版本可能如下所示:

myService.get("api/people", successCallback, errorCallback);
Run Code Online (Sandbox Code Playgroud)

我想$.ajax()直接公开内部的Deferred方法.这可能吗?

Hal*_*yon 5

你不需要改变Promises.您可以使用then的承诺.

function _validate(data, schema) {
    return false;
}

var myService = {
    get: function (data) {
        return $.ajax(data).then(function (reply) {
            if (_validate(reply, schema)) {
                return reply;
            } else {
                // works if your library is Promises/A+ compliant (jQuery is not)
                throw new Error("data is not valid JSON"); // causes the promise to fail
                /*// else do:
                var d = new $.Deferred();
                d.reject("data is not valid JSON");
                return d.promise();*/
            }
        });
    }
}

myService.get("foo").done(function () { /* success */ }).fail(function () { /*failed */ });
Run Code Online (Sandbox Code Playgroud)

  • @Halcyon:啊,非Promises/A +兼容实现的乐趣......是的,jQuery不会在`.then`中捕获抛出的错误,这与大多数promise库不同. (3认同)