Can you wait for javascript callback?

前端 未结 9 1644
故里飘歌
故里飘歌 2020-11-29 22:21

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 se

9条回答
  •  广开言路
    2020-11-29 23:11

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

提交回复
热议问题