Can you wait for javascript callback?

AlignedDev picture AlignedDev · Jan 12, 2009 · Viewed 69.4k times · Source

I'm trying to use the jQuery alerts dialog library from http://abeautifulsite.net/notebook/87 instead of the default alerts (which look pretty awful in my opinion). This seems to be a great library, but there is not an example of how to use the jConfirm library.

I need to do something like this:

function confirm() {
        var result = false;
        var response = false;
        jConfirm('are you sure?', 'Confirmation Dialog',
          function(r) {
            result = r;
            response = true;
            return r;
        });
        if (response == true) {
            alert(result);
            return result;
        }
        else {
            //wait for response
            alert('hi');
        }
    }

and my call from my .net button:

I've posted a comment on the plugin's website (just this morning) and did Google searches for javascript and waiting for a callback to complete with no results.

Any ideas on how to use the callback correctly to get the result, before the rest of the javascript executes?

Thanks.

Answer

Vincent Robert picture Vincent Robert · Jan 12, 2009

You've just hit a big limitation in JavaScript. Once your code enters the asynchronous world, there is no way to get back to a classic procedural execution flow.

In your example, the solution would be to make a loop waiting for the response to be filled. The problem is that JavaScript does not provide any instruction that will allow you to loop indefinitely without taking 100% of the processing power. So you will end up blocking the browser, sometimes to the point where your user won't be able to answer the actual question.

The only solution here is to stick to the asynchronous model and keep it. My advice is that you should add a callback to any function that must do some asynchronous work, so that the caller can execute something at the end of your function.

function confirm(fnCallback) 
{
    jConfirm('are you sure?', 'Confirmation Dialog', function(r) 
    {
        // Do something with r 

        fnCallback && fnCallback(r); // call the callback if provided
    });
}

// in the caller

alert('begin');

confirm(function(r)
{
    alert(r);

    alert('end');
})