Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

jquery - Can you wait for javascript callback?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...