Javascript function returns value.call another function according to first functions return value

StackOverflow https://stackoverflow.com/questions/19087334

Question

sorry this might not be new question but i am new to JS and i didnt get any specific examples for this.

function find(param){            
        $.each(array,function(i,elem){              
            if(elem.id==param){
                return i;
            }
        })
        return null;
    }
//after calling this function i want to perform actions based on result
$(document).on("click","#elem",function(){
      //want to make this part synchronous
      $.when(i=find(param1)).then(function{
      if(i==null)
          {//do something
          }
      else{//do something
          }
})
}

i want to perform actions based on return value of find function.and also the conditions should only be checked ater the find function is over.

Was it helpful?

Solution

Your find function will always return null.

$.each(array,function(i,elem){              
    if(elem.id==param){
        return i;   //this is each iteration callback scope not find function scope
    }
})

The find function should look like this:

function find(param){
    var matched=null;            
    $.each(array,function(i,elem){              
        if(elem.id==param){
            matched=i;
        }
    })
    return matched;
}

Hope this is helpful for you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top