拒绝jQueryajax内部的延迟

reject deferred inside jQuery ajax

本文关键字:延迟 内部 jQueryajax 拒绝      更新时间:2023-09-26

我正在使用$.ajax从服务器获取一些HTML。

我的javascript使用promise,我希望避免创建另一个promise,并使用jQueryajax,因为它已经是一个promise。

但是,有没有什么方法可以拒绝"done"回调中的承诺?

我的代码看起来像这样:

function get_html(){
   return $.ajax({ .... }).done(function(response){
     if(response.haveErrors){
       // here how do I reject and return the promise?
       return;
     }
     // code #2 should run normally
     // but can i pass a "parameter" to done() ?
   }).fail(function(){
      ....
   });
}

以及用途:

get_html().done(function(parameter){
      // code #2
    }).fail(function(){
});

此外,是否可以将参数传递给代码#2?在完成的回调中?

有没有什么方法可以拒绝"done"回调中的承诺?

不,因为done不会创建新的promise,并且只有在promise已经实现时才会被调用。您需要使用then进行链接——它创建了一个可以从回调中拒绝的新承诺。然而,对于jQuery,这有点复杂,我们不能只在回调中使用throw

所以使用

function get_html() {
    return $.ajax({…}).then(function(response) {
        if (response.hasErrors) {
            return $.Deferred().reject(response.errors);
        }
        // else
        return response; // which is getting passed as the parameter below
    });
}

然后

get_html().then(function(parameter) {
  // code #2
}, function(err) {
  // …
});

您的代码应该如下所示:

function get_html(){
    return $.ajax({ .... });
}
get_html().done(function(response){
    // process a response from your server here...
}).fail(function(){
    // process errors here...
});