locked
Wait for asynchronous operation in JavaScript (yes, again)

    Question

  • It has been said several times, I know: it's better if you implement asynchronous operations. But I think there are situations when you need to wait for an asynchronous function to finnish; for example:

    Your app loads data from a remote server; if a user searches from the desktop when your app is not active, then it must load data (said via xhr) before performing the query; it makes no sense to let the flow continue, because you will be searching in an empty structure.

    So... how do you wait for xhr to finnish before the query is performed? I have tried something like this:

        function refreshSync() {
            var refreshed = false;
            refreshAsync().then(
                function complete() {
                    refreshed = true;
                },
                function error() {
                    refreshed = true;
                }
            );
            while (!refreshed) {}
        }

    But it doesn't work; it is like if the infinite loop prevented the asynchronous function to run.

    What do you think?

     
    Thursday, January 17, 2013 3:41 PM

All replies