如何存储异步api调用的值?

时间:2015-03-31 03:17:35

标签: javascript jquery asynchronous callback promise

好的,我已经尝试了一切。我正在阅读异步调用和回调方法以及承诺和推迟变量,我似乎无法解决如何解决我的问题,即使我真的真的想学习这个。我有一个api,我需要用来获取一个对象列表,api的一部分是关注的是这样的:

/** Retrieve a list of data on the server.
     * HTTP GET to the given {@code uri} presumes that the result is XHTML unordered list of HREFs.
     * @param path (if null, default to /data) 
     * @returns callback(files[]) with file urls. */
    list: function(path, callback) {
        jquery.get(path, function(response) {

            var list = [];
            function() {//not the actual code, but it basically creates a data object and pushes it to the array 'list'
                var data = {};                      
                data.blah = blah;
                });
                list.push(data);
            });
            callback(list);
        });
    },

如何使用abode api将列表存储在我调用它之外的变量中?我的代码如下:

$("#data-tab").click(function(){

        var url = "blah.com";

        var tree = [];

        api.File.list(url, function(data){
              tree = data;
        });

        for(item in tree){//tested with this
            console.log(item.Name);//this doesnt work because tree is not populated with objects
        }
};

现在我知道我可以通过编写类似的东西来处理数据:

$.each(list, function(i, item){
    doSomething(item);
});

但是,如果我这样做,我无法使用它将对象推入数组,我需要能够访问此范围之外的此对象数组。下面的代码不起作用:

        var tree = [];
        var idDictionary = new Object();

        function addNodes(path, dictionary, object){

        if (path==null || path.length==0 || dictionary[path] != null){
            return;
        }
        var node = {
            id : path,
            text: path.substring(path.lastIndexOf('/') + 1, path.length),
            parent: path.substring(0, path.lastIndexOf('/'))
        };


        dictionary[path] = node;

        addNodes(node.parent, dictionary, null);

        };

        api.File.list(url, function(list) {
            $.each(list, function(i,object) {

                addNodes(object.id, idDictionary, object);

                });
            }); 
       for(node in idDictionary){
          tree.push(idDictionary[node]);
       }

没有任何内容存储到字典或树中。如何改进我的代码以使其有效?

0 个答案:

没有答案