I'm trying to call a function and wait for it to end. I tried to use an example that works well (in the case of one call) using 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');
}
});
});
}
what I am expecting is this :
layer1 in firstFunction
layer1 in secondFunction
layer2 in firstFunction
layer2 in secondFunction
layer3 in firstFunction
layer3 is the last layer in secondFunction
but I am getting this :
layer1 in firstFunction
layer2 in firstFunction
layer3 in firstFunction
layer1 in secondFunction
layer2 in secondFunction
layer3 is the last layer in secondFunction
EDIT :
I'm avoiding setTimeout because I'm afraid that my function will need more than the time I gave.