为什么返回'原因'来自被拒绝的jQueryAJAX调用theable

Why is the returned 'reason' from a rejected jQuery AJAX call thenable?

本文关键字:jQueryAJAX 调用 theable 拒绝 返回 原因 为什么      更新时间:2023-09-26

我最近在代码中遇到了一个与jQueryAJAX调用和承诺有关的微妙错误。简而言之,代码所做的相当于:

Promise
    .resolve($.ajax(...))
    .catch(function(err){return err})
    .then(function(response){//do something with response}

现在这样做的原因并不重要,当然,上面没有列出承诺链中的许多其他部分与问题无关。我想发生的是AJAX调用的拒绝原因,最终会出现在已解决的路径上,但每次都会再次拒绝。

我最终发现,从一个被拒绝的jQueryAJAX调用返回的响应有一个then方法,它将以自身为原因拒绝。需要明确的是:

Promise.resolve($.ajax(...)) //an ajax call which will reject
    .catch(function(err){
        err.then(null,function(err2){
            if (err===err2) console.log("AJAX error rejects with itself as a reason!");
        });
    });

将记录控制台上给出的消息。

我的问题很简单,为什么要这样做?是否有充分的理由让被拒绝的承诺本身成为可能?此外,是否也有充分的理由让这位总统以自己的理由拒绝呢?


为了避免混淆,下面是第二个代码块,重写后使用与第一个块相同的链式样式,并使用外部变量存储返回的错误。

var reason;
Promise
    .resolve($.ajax(...))
    .catch(function(err){
        reason=err;
        return err
    })
    .then(function(response){//will not be called if the ajax rejects}
    .catch(function(err){
        if (err===reason) console.log("AJAX error rejects with itself as a reason!");
    })

您的Promise错误,导致Promise在其ef中返回resolve和reject;

当你做这个

Promise.resolve($.ajax(...)) //an ajax call which will reject
.catch(function(err){
    err.catch(function(err2){
        if (err===err2) console.log("AJAX error rejects with itself as a reason!");
    });
});

您可以解析jquery-ajax调用的任何结果,它总是可以正常工作,并且您可以nr