0

我有点不确定如何问这个问题,所以我会尽可能从我所在的地方开始。我有一个数据类型,我称之为“程序”,我从单个数据源加载一些核心信息。我已经为中央数据模型制定了加载/缓存逻辑,但是我的框架需要根据项目设置将外部加载的节点附加到数据模型中。

我正在寻找的是一种设计模式,它允许我在项目需要时加载这些附加的数据节点,并且在加载所有数据之前不执行程序。我可以假设我会提前知道节点是什么以及在需要时从哪里获取数据。我当前的设置如下所示:

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
        }
    }

我当然可以解决这个问题,所以我并没有要求太多的解决方案(除非你有一些效果很好或特别优雅的东西),因为我在问是否有一个既定的模式来排队回调异步操作的集合。如果解释不清楚,我很乐意详细说明。

4

1 回答 1

1

如果使用 javascript 进行异步编程,您应该使用 Promise 模式。When.js 或 jquery.defered 可以用来解决你的问题。使用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);
            }
        )
于 2012-06-21T17:32:54.313 回答