【问题标题】:reject deferred inside jQuery ajax拒绝在 jQuery ajax 中延迟
【发布时间】:2015-06-07 04:34:14
【问题描述】:

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

我的 javascript 使用了 Promise,我想避免创建另一个 Promise 并使用 jQuery ajax,因为它已经是一个 Promise。

但是有什么方法可以拒绝“完成”回调中的承诺吗?

我的代码如下所示:

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 回调中?

【问题讨论】:

标签: javascript jquery ajax promise


【解决方案1】:

有什么方法可以拒绝“完成”回调中的承诺吗?

不,因为done 不会创建新的承诺,只有在承诺已经履行时才会被调用。您需要使用 then 进行链接 - 它创建一个新的承诺,可以从回调中拒绝。但是,使用 jQuery this is a bit more complicated,我们不能只在回调中使用 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) {
  // …
});

【讨论】:

    【解决方案2】:

    看来您的代码应该如下所示:

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

    【讨论】:

    • 我不想在那里处理来自我的服务器的响应。该 get_html 函数应该在多个地方使用。我不想在每个地方都复制代码:(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 2013-03-29
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    • 2013-07-16
    相关资源
    最近更新 更多