I had been trying to to execute a function after the other function.
function 1 This is a function that iterates through a an array of item using forEach and will return the item if the item is found in the array else it should return null
function 2 This function should execute only if the first function has completed the execution
var data = ['Test1', 'Test2', 'Test3'];
var searchfor = 'Test6';
function function1() {
var deferred = $.Deferred();
data.forEach(item => {
if (searchfor == item) {
deferred.resolve(item);
}
})
return deferred.promise();
}
function function2() {
function1().then(function function3(result) {
if (result == null) {
alert("Sorry unable to find the user")
} else {
alert("user " + result + " has been found");
}
})
}
function2();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I need to wait until all the items in data is iterated in function1 before executing function3. So as the code shows if an item is present in the array then the if condition in the foreach loop runs and the deferred is resolved, but what if the item is not found in the foreach loop? So how can I wait until all the items in the array is iterated before the function3 is executed so that I can print an item not found or print the item if found