I know the remended 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 plete before continuing with the current thread. Here's an example (plete example at /)
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 acplish this?
I know the remended 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 plete before continuing with the current thread. Here's an example (plete example at http://jsfiddle/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 acplish this?
Share Improve this question asked Sep 27, 2012 at 17:43 Jeremiah OrrJeremiah Orr 2,6301 gold badge20 silver badges25 bronze badges 1- 3 I don't know what your deferred does, but seems like you should get rid of it. Deferreds are for non-blocking, async behaviors. – bfavaretto Commented Sep 27, 2012 at 17:48
1 Answer
Reset to default 5I 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.