我有点不确定如何提出这个问题,所以我会尽可能地从我所处的位置开始。我有一个数据类型,我称之为“程序”,我从一个数据源加载一些核心信息。我为中央数据模型制定了加载/缓存逻辑,但是我的框架需要根据项目设置将外部加载的节点附加到数据模型。
我正在寻找的是一种设计模式,它允许我在项目需要时加载这些附加的数据节点,并且在加载所有数据之前不执行程序。我可以假设我会事先了解节点的内容以及在需要时从何处获取数据。我目前的设置如下所示:
var programs = {},
loadCuePoints = function (uuid, callback) {
//will call the callback with the data once loaded and add the program
//to programs, keyed by the uuid
},
loadLinkedFiles = function (uuid, callback) {
//will append the data to programs[uuid] and call the callback with the
//data once loaded
},
loadProgram = function (uuid, callback) {
//will append the data to programs[uuid] and call the callback with the
//data once loaded
},
// hash where the key is the node on program and the value is the function
// used to load the data, this will be based on project settings, but I'm not
// concerned with this logic for this question
requiredData = {
cuePoints : loadCuePoints,
linkedFiles : loadLinkedFiles
},
getProgram = function(uuid, callback) {
if (programs[uuid]) {
callback(programs[uuid]);
} else {
//assume the key in the requiredData hash is the required node on
//Program, and that the value is the callback method, the functions
//in this table sre already set up to load the data and return it
//via the callback once loaded
}
}
我当然可以通过这种方式破解我的方式,所以我不是要求解决方案这么多(除非你有一些非常好或者特别优雅的东西),因为我在问是否有一个已建立的排队模式一组异步操作后的回调。如果解释不清楚,我很乐意详述。
答案 0 :(得分:1)
如果使用javascript进行异步编程,则应使用promise模式。 When.js或jquery.deferred可用于解决您的问题。使用jquery的伪代码写在下面
function oneArrayJquery(value) {
var deffered = jQuery.Deferred();
deffered.resolve(value);
return deffered;
}
function loadAllArrayValues(imagearray) {
var deffered = [];
for (var i = 0; i < imagearray.length; i++) {
deffered.push(oneArrayJquery(imagearray[i]));
}
return deffered;
}
var arrayvalue = [1, 3, 4];
jQuery.when(loadAllArrayValues(arrayvalue)[0], loadAllArrayValues(arrayvalue)[1]).then(function (value1,value2) {
alert(value1);
}
)