每次在循环JavaScript中运行时,等待函数结束

时间:2019-01-10 17:37:14

标签: javascript jquery promise

我正在尝试调用一个函数并等待其结束。我尝试使用一个使用promises很好(在一个电话的情况下)的示例。

function firstFunction(layer)
{
    // I want to make some requests to my server which i don't know how much time it'll take
    console.log(layer + ' in firstFunction');
    var deferred = $.Deferred();
    deferred.resolve();
    return deferred.promise();
}

function secondFunction()
{
    var layers=['layer1','layer2','layer3'];
    var promise = null;
    layers.forEach(function(layer,idx,array) {
        promise = firstFunction(layer);
        promise.then(function(result) { 
            if (idx === array.length - 1){ 
                console.log(layer ' is the last layer in secondFunction');
            }
            else{
                console.log(layer+' in secondFunction');
            }
        });
    });
}

这是我的期望:

layer1 in firstFunction
layer1 in secondFunction
layer2 in firstFunction
layer2 in secondFunction
layer3 in firstFunction
layer3 is the last layer in secondFunction

但是我得到这个:

layer1 in firstFunction
layer2 in firstFunction
layer3 in firstFunction
layer1 in secondFunction
layer2 in secondFunction
layer3 is the last layer in secondFunction

编辑:
我避免使用setTimeout,因为我担心我的函数所需要的时间将超过我给定的时间。

0 个答案:

没有答案