Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I block until Dojo Deferred is resolved?

I know the recommended use case for Dojo Deferreds is to use dojo.when(def) or def.then() and provide a callback for when the Deferred is resolved. However, sometimes I run into scenarious where I really need to wait for that Deferred to complete before continuing with the current thread. Here's an example (complete example at http://jsfiddle.net/DG3Ax/2/)

function getSomething() {
    var def = getSomeDeferred();

    def.then(function(result) {
        dojo.place("<li>def.then() = " + result + "</li>", "output");
    });

    return def.gimmeTheResultNow();
}

dojo.place("<li>getSomething() = " + getSomething() + "</li>", "output");

Obviously Deferred.gimmeTheResultNow() does not exist, but that's the functionality I'm looking for. I don't have control of the code calling getSomething(), so I can't make it handle a Deferred; it needs the real result.

I know xhrGet() has a sync parameter that I think would do the job if this were an AJAX call, but that isn't necessarily the case. Is there any other way to accomplish this?

like image 598
Jeremiah Orr Avatar asked Sep 27 '12 17:09

Jeremiah Orr


1 Answers

I got a very helpful answer from the dojo-interest mailing list, so I thought I'd stick it here:

Unfortunately, you can't do this in the browser.

JavaScript in the browser is single-threaded. If you're sitting waiting for a Deferred to resolve, then you're using that thread. This is the same thread that will be needed somewhere down the line to service a call to Deferred.resolve() (which, itself, would then result in a call to the function that you passed to .then()).

You can call xhr synchronously because the base implementation of the XHR get allows you to call it synchronously. The functionality of dojo/Deferred is just a wrapper around the XHR internals.

like image 187
Jeremiah Orr Avatar answered Sep 28 '22 02:09

Jeremiah Orr