0

我正在尝试在多个函数中获取一些数据,并希望将它们链接起来,以便仅在正确加载所有数据时才执行最后一个函数。

问题是 .done() 部分中的函数将立即被调用,而不是等到 Deferred-Object 被解决。我也尝试过用 .then() 链接它们,但这也没有用。

var array1, array2;

function doStuffWithReceivedData() {
    // Working with the data
}

function getArray1() {
    var defArray1 = $.Deferred();

    $.getJSON(url, function(data) {
        if (data.success) {
            array1 = data.payload;
            defArray1.resolve();
        } else {
            // Information displayed that there was an error
        }
    })

    return defArray1;
}

// Function 2 is like the first one
function getArray2() {...};

$(document).read(function() {
    getArray1()
        .done(getArray2()
            .done(doStuffWithReceivedData()));
}
4

1 回答 1

1

to 的参数.done()必须是一个函数。您正在调用该函数,而不是传递它。去掉括号。

$(document).ready(function() {
    getArray1()
        .done(function() {
            getArray2().done(doStuffWithReceivedData));
        }
}
于 2017-09-05T09:56:13.383 回答