gpt4 book ai didi

javascript - 使用 Ajax 调用处理超时

转载 作者:行者123 更新时间:2023-12-05 06:47:46 26 4
gpt4 key购买 nike

我不是 JS 专家(可以写一些基本的东西),我正在努力将我们的支付 API 与前端集成,作为流程的一部分,我们希望触发超时以防我的后端支付 API在给定的时间范围内没有响应。这是与支付 API 交互的 JS 代码。

performAuthorizePaymentRequest: function (payment) {
return new Promise(function (resolve, reject) {
$.ajax({
type: 'POST',
url: encodedContextPath + '/checkout/authorise_order',
data: JSON.stringify(payment),
dataType: 'json',
contentType: 'application/json',
success: resolve,
error: reject,
always: function () {
pageSpinner.end()
},
timeout: 30000 /* call this.session.completePayment() within 30 seconds or the payment is cancelled */
});
});
}

这似乎工作正常,但我看到了以下问题。

  1. 万一 m 支持的 API 抛出任何错误,代码仍在等待超时。
  2. 即使对于成功案例,js 也会在显示成功消息之前等待超时。

有办法解决吗?如果我在这里做错了什么,请告诉我。

注意:此代码只会在Safari上执行,其他浏览器不可用

最佳答案

您可以使用 XMLHttpRequest 对象的 abort 方法,然后设置超时以在 30 秒后中止请求。像这样:

var requestObj = $.ajax({
...
)};
setTimeout(function(){
requestObj.abort();
}, 30 * 1000); // 30 seconds

参见 XMLHttpRequest.abort reference


另一种方法是通过将状态标志设置为“超时”,使 success 函数在 30 秒后停止工作。请参阅以下代码中的注释:

/* Use this variable to check whether we are within 30 minutes. This can be:
'still in time': the original state, waiting for a response
'out of time': we passed the 30 minutes, don't do anything with a possible success response and call the reject function
'already resolved': resolved within 30 minutes, no need to reject after 30 minutes
*/
var timeStatus = 'still in time';
/* Time until timeout */
var timeoutTime = 30 * 1000; //30 seconds
/* Save the request */
var theRequest = $.ajax({
...
/* In success we must check if we are still in time */
success: function(data, textStatus, jqXHR){

if(timeStatus === 'out of time'){
// BAIL OUT. Do nothing since this has alreay been rejected in the setTimeout function. */
console.log("bailing out. 30 minutes exceeded");
return false;
}
else{
/* Set to 'already resolved' so our setTimeout function doesn't reject. */
timeStatus = 'already resolved';
resolve(data, textStatus, jqXHR);
}
},
/* In error we do the same 'out of time' check */
error: function (jqXHR, errorCode, error){
if(timeStatus === 'out of time'){
// BAIL OUT. Do nothing since the request has alreay been rejected in the setTimeout function. */
console.log("bailing out. 30 minutes exceeded");
return false;
}
else{
/* Set to 'already resolved' so our setTimeout function doesn't reject. */
timeStatus = 'already resolved';
reject(jqXHR, errorCode, error);
}
}
});
/* After 30 minutes set the timeStatus to 'out of time' so we can cut off incoming ajax responses. */
setTimeout(function(){
if(timeStatus !== 'already resolved'){
timeStatus = 'out of time';
reject(theRequest, 'timeout','');
}
}, timeoutTime);

关于javascript - 使用 Ajax 调用处理超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66977220/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com