gpt4 book ai didi

javascript - JQuery/Ajax 和 when/done/promise 混淆

转载 作者:行者123 更新时间:2023-12-03 06:51:25 27 4
gpt4 key购买 nike

我正在努力实现以下目标:1)从一些来源获取数据并“用它做点什么”。2)从其他来源获取数据并“用它做点什么”。3)数据获取最好应该异步运行(同时,第二个数据不应等待第一个数据完成)。4)当两者都完成时,一些业务逻辑运行 - 但仅当它们完成时。

我创建了一个小的 JSFiddle 来展示我认为这是如何工作的 - 但不幸的是它不起作用:a) 数据获取调用按顺序执行。b) 上述步骤 4 中的业务逻辑在数据获取开始之前执行...

在这里摆弄:https://jsfiddle.net/LeifFrederiksen/emttmhm7/

$.when(
getOneThing(),
getAnotherThing()
).done(
function() {
console.log("Got it all");
$("#Output").append("<BR>Got it all");
}
);

function getOneThing() {
commonFunctionToGetStuff("oneKindOfThings",renderOneKindOfThings);
}

function getAnotherThing() {
commonFunctionToGetStuff("anotherKindOfThings",renderAnotherKindOfThings);
}

function commonFunctionToGetStuff (listTitle,successFunction) {
var url = "https://httpbin.org/get";

$.ajax({
url: url,
type: "GET",
headers: { "accept": "application/json;odata=verbose" }
}).success(function (data) {
console.log("Calling renderfunction for " + listTitle);
$("#Output").append("<BR>Calling renderfunction for " + listTitle);
successFunction(data);
console.log("Back from renderfunction for " + listTitle);
$("#Output").append("<BR>Back from renderfunction for " + listTitle);
});
}

function renderOneKindOfThings(data) {
// Do something with the data...
console.log("Doing oneKindOfThings.");
$("#Output").append("<BR>Doing oneKindOfThings.");
}

function renderAnotherKindOfThings(data) {
// Do something with the data...
console.log("Doing anotherKindOfThings.");
$("#Output").append("<BR>Doing anotherKindOfThings.");
}

我们非常感谢任何有助于阐明结构的帮助。

我需要维护这样的结构,其中执行实际 Ajax 调用的函数是通用的,并且可以通过简单的包装函数进行调用,参数控制要使用的数据源 - 就像示例中那样:-)

问候莱夫

最佳答案

您需要从您的 commonFunctionToGetStuff 方法以及调用它的方法返回 promise 。否则,您将 undefined 传递到 when 函数中,该函数将立即执行完成回调。此外,您还有一些错误的回调名称(是 donethen,而不是 success)。

function getOneThing() {
return commonFunctionToGetStuff("oneKindOfThings",renderOneKindOfThings);
}

function getAnotherThing() {
return commonFunctionToGetStuff("anotherKindOfThings",renderAnotherKindOfThings);
}

function commonFunctionToGetStuff (listTitle,successFunction) {
var url = "https://httpbin.org/get";

return $.ajax({...})
.then(function (data) { ...});
}

关于javascript - JQuery/Ajax 和 when/done/promise 混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37482339/

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