gpt4 book ai didi

javascript - Promises 和重复的 AJAX 调用

转载 作者:行者123 更新时间:2023-11-30 05:37:49 24 4
gpt4 key购买 nike

我正在尝试提出一个函数,其签名与 jQuery.ajax 相同。它是一个单独的函数,因为根据响应中的 HTTP 状态,它应该完成并解决返回的 promise ,或者发出具有相同参数的延迟后续 AJAX 请求(因此重复)。虽然我有一个可行的解决方案,但我觉得它是一个 promise 反模式,因为我明确调用 $.Deferred() 来表示流程的状态。问题:

  • 是否可以重用 $.ajax 调用返回的“thenable”对象,就像链接后续调用返回的 promise 一样?
  • 每次调用另一个 $.ajax 时,您将如何在 promise 链上合并一个 progress 调用?

请引用我的功能:

callAPI = function(jqAjaxOptions, deferred) {
if (deferred == null) {
deferred = $.Deferred();
}
$.ajax(jqAjaxOptions).always(function(data, status, xhr) {
var args;
args = _.toArray(arguments);
switch (xhr.status) {
case 200:
return deferred.resolve.apply(deferred, args);
case 201:
case 202:
return setTimeout(function() {
return callAPI(jqAjaxOptions, deferred);
}, 2000);
default:
deferred.reject.apply(deferred, args);
if (data.responseText) {
return app.notifier.set(JSON.parse(data.responseText));
} else {
return app.notifier.set({
title: "Couldn't contact data server.",
content: "It seems the API server is down. Please contact the DAV team."
});
}
}
});
return deferred.promise();
};

最佳答案

Is it possible to reuse the „thenable” object returned by the $.ajax calls, as in chaining up the promises returned by subsequent calls?

是和否。您会丢失多个参数,并且无法发出进度事件。它看起来像这样:

function timeout(ms) {
var d = $.Deferred();
setTimeout(d.resolve, ms);
return d.promise();
}
function callApi(ajaxOptions) {
function tryit () {
return $.ajax(ajaxOptions).then(data) {
if (this.status == 200)
return data;
else if (this.status == 201 || this.status == 202)
return timeout(2000).then(tryit);
else
return $.Deferred().reject(this.responseText
? JSON.parse(this.responseText)
: {
title: "Couldn't contact data server.",
content: "It seems the API server is down. Please contact the DAV team."
});
});
}
return tryit();
}

How would you go about incorporating a progress call on the promise chain each time another $.ajax is called?

只需调用 notify :

function callApi(ajaxOptions) {
var deferred = $.Deferred();
function tryit() {
$.ajax(jqAjaxOptions).always(function() {
switch (this.status) {
case 200:
return deferred.resolveWith(this, arguments);
case 201:
case 202:
deferred.notify("Next try in 2s");
return setTimeout(tryit, 2000);
default:
deferred.notify(this.responseText
? JSON.parse(this.responseText);
: {
title: "Couldn't contact data server.",
content: "It seems the API server is down. Please contact the DAV team."
});
deferred.rejectWith(this, arguments);
}
});
}
tryit();
return deferred.promise();
}

关于javascript - Promises 和重复的 AJAX 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22503657/

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