JQuery/Ajax 和 when/done/promise 混淆

JQuery/Ajax and when/done/promise confusion

我正在尝试完成以下任务: 1) 获取数据源和 "do something with it"。 2) 从其他来源获取数据 "do something with it"。 3) 数据获取最好 运行 异步(同时,即第二个不应该等待第一个完成)。 4) 当两者都完成时,一些业务逻辑 运行s - 但只有当它们完成时。

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

Fiddle 这里: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 调用的函数是通用的,可以通过简单的包装函数调用,参数控制要使用的数据源 - 就像它在例子:-)

问候 莱夫

您需要 return 来自您的 commonFunctionToGetStuff 方法和调用它的方法的承诺。否则,您会将 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) { ...});
}