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

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

  •  02-04-2022
  •  | 
  •  

Question

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;
     } 
Was it helpful?

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;
} 

OTHER TIPS

Generally you can't, this is the main gotcha of asynchronous programming. Technically you can make the AJAX call be synchronous, but that's a bad idea. Instead isDead() will need to accept a callback to receive its answer

function isDead(id, callback) {
    PeopleManager.isPersonDead(id, function(result) {
        callback(result === 1);
    });
}

Some details have been left out, but that's the general idea. You can also look into promises for a more modern approach to this problem

Use a promise instead.

Read the article if you are unfamiliar with promises. To get an example related to your question jump to the section "Accept Promises As Parameters"

http://www.kendoui.com/blogs/teamblog/posts/13-03-28/what-is-the-point-of-promises.aspx

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