微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

JavaScript承诺.then()和.catch同时触发

我正在将关于wordpress评论转变为ajax驱动的系统.

到目前为止一切都很好,直到我遇到.catch()方法在.then()方法之后直接触发的问题.

这是我的代码……

Ajax引擎

commentAPI: function(action, encoded, userID) {
    let self = this;

    return new Promise(function (resolve, reject) {
       //console.log("ajax call to " + self.ajaxURL + " with action " + action);

        jQuery.ajax({               
            url: self.ajaxURL,
            type: 'post',
            data: 'action='+action+'&data='+encoded,
            dataType: 'json',
            success: function(data, code, jqXHR) { resolve(data); },
            fail: function(jqXHR, status, err) { console.log('ajax error = ' + err ); reject(err); },
            beforeSend: function() {} //display loading gif
        });
    });
}, 

处理评论表单提交的方法

handleReplyFormSubmit: function(form) {
    let self = this;

    this.removeErrorHtml(form);

    // Serialize form to name=value string
    const formdata = jQuery(form).serialize();

    // Validate inputs
    // * wordpress doing this for Now and providing error resonse 

    // Encoode data for easy sending
    const encodedJSON = btoa( formdata );

    this.commentAPI('dt_submitAjaxComment', encodedJSON).then(function(response){
        console.log('firing then');

        if( response.error == true ) {
            self.printFormError(form, response.errorMsg);
        }

        else { 
            let html = response.commentHTML;
            console.log('html returned' + html)
            jQuery(form).append(html);
            Jquery(form).remove();
        }

    }).catch(function(err) {            
        console.log('firing catch');

        if( err !== undefined && err.length > 0 ) { 
            self.printFormError(form, err);
        }

        else { 
            self.printFormError(form, 'Unkown error');
        }
    });

    return false;
},

代码正在做它应该做的事情,但是catch方法也被解雇了,这使得错误处理令人沮丧……

Output of code. Notice the console.log('firing catch') is being fired

注意这是如何被解雇的

console.log('firing catch')

但这不是(在ajax失败函数内)

console.log('ajax error = ' + err );

难道我做错了什么?

解决方法:

承诺

通常会触发然后触发:这意味着在当时的处理程序代码中遇到了一些错误,因此catch会触发. Catch处理程序将触发:

>如果异步操作中存在错误,则拒绝Promise.
>如果先前的处理程序中存在错误.

那么,以下代码

Promise.resolve()
.then( () => {
  console.log('this will be called');
  throw new Error('bum');
  console.log('this wont be logged');
})
.catch(err => {
  console.log('this will be logged too');
  console.log(err); // bum related error
});

将从那时开始生成日志并捕获处理程序.

你的代码

在你的处理程序里面有这样的代码

    else { 
        let html = response.commentHTML;
        console.log('html returned' + html)
        jQuery(form).append(html);
        Jquery(form).remove();
    }

注意最后一行是如何使用Jquery而不是jQuery,这是一个错字.我敢打赌这是导致火灾发生的错误.

最重要的是

jQuery的现代版本只返回$.ajax()的承诺,因此不需要将它包装到另一个承诺中.

这段代码

commentAPI: function(action, encoded, userID) {
  let self = this;

  return new Promise(function (resolve, reject) {
  //console.log("ajax call to " + self.ajaxURL + " with action " + action);

    jQuery.ajax({               
        url: self.ajaxURL,
        type: 'post',
        data: 'action='+action+'&data='+encoded,
        dataType: 'json',
        success: function(data, code, jqXHR) { resolve(data); },
        fail: function(jqXHR, status, err) { console.log('ajax error = ' + err ); reject(err); },
        beforeSend: function() {} //display loading gif
    });
  });
},

应该只是:

commentAPI: function(action, encoded, userID) {
    return jQuery.ajax({
        url: this.ajaxURL,
        type: 'post',
        data: 'action='+action+'&data='+encoded,
        dataType: 'json',
        beforeSend: function() {} //display loading gif
    });
},

因此,您可以处理commentApi中的成功和失败,然后捕获处理程序,而不是传递成功和失败回调来解析或拒绝包装Promise.

ajax的成功助手

成功回调参数有三个参数.然而,Promises通常只需要一个.

但是,jQuery确实将相同的三个参数传递给then处理程序,因此如果您需要访问它们,您仍然可以在处理程序中使用它们:

this.commentAPI('dt_submitAjaxComment', encodedJSON).then(function(data, code, jqXhr){
 // the three arguments will be accessible here.
...
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐