我试图找出处理这种情况的最佳方法。基本上我希望流程像这样工作:
1.) 从服务器获取配置数据(异步)
2.) 接收到配置数据后运行 doStuff()(异步)
3.) 在 doStuff() 完成后运行 postResults
目前我似乎使用 PubSub.js 让这个流程工作,但是我试图弄清楚如何将配置数据 (#1) 的结果提供给 postResults (#3)。虽然我似乎有使用 PubSub 的流程,但我不确定如何从 postResults (#3) 访问配置 (#1) 回调数据
这是代码摘要:
PubSub.subscribe('config', doStuff());
fetchConfigurations();
function fetchConfigurations () {
var req = new XMLHttpRequest();
var url = CONFIGURATION_SERVER_URL;
req.onreadystatechange = function() {
if (req.readyState == 4 && req.status == 200) {
var configObject = eval('(' + req.responseText + ')');
PubSub.publish('config', configObject);
} else {
console.log("Requesting config from server: " + url);
}
}
req.open("GET", url, true);
req.send(null);
}
function doStuff() {
PubSub.subscribe('results', postResults);
var results = {};
// do some async work...
results['test1'] = "some message";
results['test2'] = "another message";
PubSub.publish('doStuff', results);
}
function postResults (doStuffId, doStuffData) {
var req = new XMLHttpRequest();
var url = TEST_RESULTS_URL; // I want to get this from the configObject is get in fetchConfigurations
req.open("POST",url,true);
req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
req.send(doStuffData['test1'] + doStuffData['test2']);
}