Can you wait for javascript callback?

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

Leave a Comment