Chain of Jquery Promises

后端 未结 2 385
情歌与酒
情歌与酒 2021-01-02 00:26

I have a simple chain of events:

  1. Get Columns from a metaData table (async)
  2. load selected columns (async)
  3. render list

I used t

相关标签:
2条回答
  • 2021-01-02 00:29

    It should be something like:

    function getColumnsFromMeta()
    {
        var d = $.Deferred();
    
        // retrieve data in async manner and perform
        // d.resolve(columns);
    
        return d.promise();
    }
    
    function loadSelectedColumns(columns)
    {
        var d = $.Deferred();
    
        // retrieve data in async manner and perform
        // d.resolve(data);
    
        return d.promise();
    }
    
    function render(data)
    {
        // render your data
    }
    
    getColumnsFromMeta().pipe(loadSelectedColumns).pipe(render);
    

    http://jsfiddle.net/zerkms/xYDbm/1/ - here is a working sample

    http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/ -- this is the article I really like about promises

    0 讨论(0)
  • 2021-01-02 00:47

    zerkms's reply helped me after some thought. I'm going to post what I did here in case an example with full context is helpful.

    /**
     * takes a list of componentIDs to load, relative to componentRoot
     * returns a promise to the map of (ComponentID -> componentCfg)
     */
    function asyncLoadComponents (componentRoot, components) {
    
        var componentCfgs = {};
    
        function asyncLoadComponentCfg(component) {
            var url = _.sprintf("%s/%s", componentRoot, component);
            var promise = util.getJSON(url);
            promise.done(function(data) {
                componentCfgs[component] = data;
            });
            return promise;
        }
    
        var promises = _.map(components, asyncLoadComponentCfg);
        var flattenedPromise = $.when.apply(null, promises);
        var componentCfgPromise = flattenedPromise.pipe(function() {
            // componentCfgs is loaded now
            return $.Deferred().resolve(componentCfgs).promise();
        });
    
        return componentCfgPromise;
    }
    
    
    var locale = 'en-US';
    var componentRoot = '/api/components';
    var components = ['facets', 'header', 'DocumentList'];
    $.when(asyncLoadComponents(componentRoot, components)).done(function(componentCfgs) {
        buildDocumentListPage(locale, componentCfgs)
    });
    
    0 讨论(0)
提交回复
热议问题