我正在创建一个带有动态选项卡(来自 RESTful 的数据)的 Web 应用程序,每个选项卡都有一个 dgrid,我从 RESTful 获取列,也从 RESTful 获取行。我使一切都可以与 XHR 和 MemoryStore 配合使用,但我现在需要从 XHR 更改为 JsonRest,因为我需要向服务器传递一个 HTTP Range。
我在使用 Dojo 中的异步调用来组织代码时遇到困难。我给你举个例子:
method1() - Sync
method2() - Async (JsonRest)
method3() - Sync
仅在 method2() 准备就绪后执行 method3() 的最佳方式是什么?
我找到了一个名为 WHEN 的类。看起来不错。但是如何在 dojo 中使用异步应用程序呢?
我现在最大的问题:我无法通过方法分离我的代码,我需要将所有代码放在 JsonRest 的 Promise 函数中(THEN)。因为在 THEN 内部我无法访问其他方法。
最佳答案
我同意使用 Dojo 的 Promise 实现的建议。
如果您不习惯 promise ,这可能会帮助您更快地理解它:http://jsfiddle.net/27jyf/9/ 。它的另一个不错的功能是错误处理,我鼓励您在了解基本排序后阅读此内容。
require(["dojo/Deferred", "dojo/when"], function(Deferred, when) {
var sayHello = function() { return 'hello' };
var sayWorld = function() {
var deferred = new Deferred();
window.setTimeout(function() {
deferred.resolve('world');
}, 1000);
return deferred.promise;
};
var sayBang = function() { return '!' };
//This will echo 'hello world !'
//That's probably how you want to sequence your methods here
var message = [];
message.push(sayHello());
sayWorld().then(function(part) {
message.push(part);
message.push(sayBang());
console.debug(message.join(' '));
});
//This will also echo 'hello world !'
//This probably not the syntax that you want here,
//but it shows how to sequence promises and what 'when' actually does
var message2 = [];
when(sayHello())
.then(function(part) {
message2.push(part);
return sayWorld();
})
.then(function(part) {
message2.push(part);
return when(sayBang());
})
.then(function(part) {
message2.push(part);
console.debug(message2.join(' '));
});
//Provided the behavior observed above, this will echo 'hello !'
//dojo/when allows you to use the same syntax for sync and async...
//but it does not let you magically write async operations in a sync syntax
//'world' will be pushed into the array a second later, after the message has already been echoed
var message3 = [];
message3.push(sayHello());
when(sayWorld(), function(part) {
message3.push(part);
});
message3.push(sayBang());
console.debug(message3.join(' '));
});
关于javascript - 如何用Dojo组织异步代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14416119/