ajax success then,javascript - jQuery AJAX relation between success and .then - Stack Overflow

本文探讨了一个关于JavaScript中使用AJAX进行请求的问题。作者遇到的情况是,当AJAX请求失败时,希望自动重试并在所有重试失败后才调用错误处理函数。目前的代码导致重试三次后,错误处理立即被调用。为解决这个问题,需要调整代码以确保只有在所有重试都失败后才执行错误回调。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I'm trying to solve a very simple problem, but I can't figure it out.

I have following code:

TEST

var counter = 0;

function test() {

return $.ajax({

url: "https://127.0.0.1:4432",

success: function(html){

console.log('success! test');

},

error: function() {

if (counter++ < 3) {

console.log("Retrying");

$.ajax(this);

return;

}

console.log('ERROR! test');

}

});

}

function run() {

test()

.then(

function(){console.log('finished ALL OK')},

function() {console.log('finished all ERROR')

;});

}

What I want to achieve is that after clicking on the button, the AJAX request will be sent to server. In case of failure of the AJAX the request will be retried. Only after all retries will be finished, then the success or failure in the ".then" function will be called .

At this moment, the code behaves like that the AJAX call is retried three times, but the ".then()" handler is called right after first failure.

In console of the browser it looks like this:

aebb8dbe906f093ef8015caaca38f120.png

I would like to see the "finished all ERROR" text at the end after all retries.

Hope this makes sense and I will be grateful for any help.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值