javascript - 在 Dojo Deferred 解决之前我如何阻止?

标签 javascript dojo deferred

我知道 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/

相关文章:

javascript - 如何使 Node.js 本地主机公开

javascript - 数据表服务器端获取第 0 行请求的未知参数 '0' 错误

dojo - dojo/domReady 是做什么的?

proxy - Scrapyd 重试如果在扭曲的延迟中出现错误/无法打开 CONNECT 隧道错误

angularjs - Foreach 进入带有 $http promise 的 foreach

javascript - jquery 中链式延迟的条件

javascript - 如何配置 Firefox 以允许 Javascript 拦截从剪贴板粘贴的值?

javascript - 如何将json数据发送到可序列化类

javascript - dojo 中是否可以区分程序滚动和用户滚动?

javascript - 点击 map 外部打开 Google map 信息窗口