在循环的每次迭代中等待 async .done()

Wait for async .done() in every iteration of loop

所以,我有这样的锁定功能:

function getMainData() {
    var dfd = $.Deferred();

    $.getJSON('My string that i pass',
        function(result) {
            if (result !== undefined) {
                dfd.resolve(result);
            }
        })

    return dfd.promise()
}

function getSpecificData() {
    var dfd = $.Deferred();

    var myArray = [];

    for (var i = 0; i < 5; i++) {
        getMainData().done(function(result) {
            myArray.push(result)

            dfd.resolve(myArray) //This is where I am lost.
        })
    }

    return dfd.promise()
}

getSpecificData().done(function(result) {
    console.log(result);
})

我想我知道如果将 promise 链接在一起是如何工作的,但我无法让 for 循环等待异步调用在下一次迭代之前完成。

有人能帮帮我吗?

你试过没有 promise 比如 :

var myArray = [];
var cpt=0;
var total=5;

getMainData();
console.log(myArray);

function getMainData() 
{
    $.getJSON('My string that i pass', function(result) {
        if(cpt<total)
        {
            myArray.push(result);
            cpt++;

            getMainData();
        }
    })
}

希望对您有所帮助。

您应该改为将所有承诺推送到数组中并等待所有承诺完成。

function getMainData() {
    return $.getJSON('My string that i pass');
}

function getSpecificData() {
    var promiseArray = [];

    for (var i = 0; i < 5; i++) {
        promiseArray.push(getMainData());
    }

    return $.when.apply($, promiseArray);
}

getSpecificData().done(function(result) {
    console.log(result);
})

for 循环无法延迟下一次迭代以等待异步代码。

你可以使用递归调用的函数来解决

function getMainData() {
    return $.getJSON('My string that i pass');
}

function getSpecificData() {
    var myArray = [], def = new $.Deferred();

    (function rec(i) {
        getMainData().done(function(result) {
            myArray.push(result);
            if (i < 5 && result !== undefined) {
                console.log(i)
                rec(++i);
            } else {
                def.resolve(myArray);
            }
        });
    })(0);

    return def.promise();
}

getSpecificData().done(function(result) {
    console.log(result);
});