我知道 Dojo Deferred 的推荐用例是使用 dojo.when(def) 或 def.then() 并在解析 Deferred 时提供回调。但是,有时我会遇到这样的情况,我真的需要等待 Deferred 完成才能继续当前线程。这是一个示例(完整示例位于 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");
显然 Deferred.gimmeTheResultNow()
不存在,但这是我正在寻找的功能。我无法控制调用 getSomething() 的代码,所以我无法让它处理 Deferred;它需要真正的结果。
我知道 xhrGet() 有一个同步参数,如果这是一个 AJAX 调用,我认为它可以完成这项工作,但事实并非如此。有没有其他方法可以做到这一点?
最佳答案
我有一个 very helpful answer来自 dojo-interest 邮件列表,所以我想我会把它贴在这里:
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.
关于javascript - 在 Dojo Deferred 解决之前我如何阻止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12627165/