Search code examples
javascriptjqueryajaxdwr

How can I make a function wait for the ajax call to return a value before returning true or false?


edit: the two questions linked above are not like what I need. I don't have a URL instead Im using DWR to call the java object directly from javascript so they don't help me.

I want to check if a person is dead many times on a page and I wan to reuse a function so I dont have to write the ajax stuff many times. I want to reuse isDead()

The problem is it always returns false because it doesn't wait for the ajax callback.

How can I make it wait before returning true or false?

function isDead(personId){
        PeopleManager.isPersonDead(personId,{
            callback : function(result)
            {
                if(result == 1){
                    //dead
                    return true;
                }else{
                    //alive
                    return false;
                }
            },
            errorHandler : function(e){
                alert(e); 
                }
        });

        return false;
     } 

Solution

  • Luckily for me there is an answer specific to DWR. It turns out you can disable the asynchronous functionality with async:false

    function isDead(personId){
        DWREngine.setAsync(false);
                PeopleManager.isPersonDead(personId,{
                    callback : function(result)
                    {
                        async:false,
                        if(result == 1){
                            //dead
                            return true;
                        }else{
                            //alive
                            return false;
                        }
                    },
                    errorHandler : function(e){
                        alert(e); 
                        }
                });
        return false;
    }