1

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

Shiladitya
  • 12,003
  • 15
  • 25
  • 38
  • you may use reject() and [.fail()](https://api.jquery.com/deferred.fail/) or you may resolve with a special value.... – gaetanoM Mar 22 '19 at 15:20
  • Instead of `forEach()`, use `find()` and don't return a promise. There's no need to use a promise here. – Patrick Roberts Mar 22 '19 at 15:40
  • @gaetanoM Yes I can reslolve wit a special value but the thing is I have to wait till the last iteration to confirm that the item is not present in the array. Could you please provide me an example? – Varun James Mar 23 '19 at 08:02
  • @Patrick , So does using find instead of foreach wait for the whole array to be iterated before the rest of the code is executed? – Varun James Mar 23 '19 at 08:03
  • 1
    No, `find()` returns as soon as one element matches. – Patrick Roberts Mar 23 '19 at 08:15
  • @PatrickRoberts But what if the item is not found in the list. will it return. Can you please show me a code sample? – Varun James Mar 23 '19 at 10:19

0 Answers0