Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chain of Jquery Promises

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 to just the chain these functions, each calling the next when it had completed. However, its not very obvious what's going (calling getColumnsFromMeta results in the view being populated). So in the interest of clarity and code re-use I'd like to refactor these using JQuery Promises. I have used promises before. But how do I chain more than two? getColumnsFromMeta ().then(loadSourceFromDatabase /*some arguments*/) //.then(renderList)?;

Here's an example of the getColumnsFromMeta:

var getColumnsFromMeta = function(id)
{
    var sql,
        dfd;

    dfd = $.Deferred();

    var onSuccess = function(tx, result)
    {
        var columns = [];

        for (var i = 0; i < result.rows.length; i++) 
        {
            columns.push(result.rows.item(i).Column);
        }

        dfd.resolve(columns);
    };

    var onError = function(tx, error)
    {
        dfd.reject(error);
    };

    sql = "SELECT Column FROM Meta WHERE id = ?";

    database.query(sql, [id], onSuccess, onError);

    return dfd.promise();
};
like image 469
Jon Wells Avatar asked Jul 18 '12 10:07

Jon Wells


People also ask

What are jQuery promises?

promise() method returns a dynamically generated Promise that is resolved once all actions of a certain type bound to the collection, queued or not, have ended. By default, type is "fx" , which means the returned Promise is resolved when all animations of the selected elements have completed.

Is jQuery Ajax a promise?

jQuery have promises implemented with their AJAX methods. In a nutshell, they are utilities that allow us to work with events that have completed or put them in queues or chain them – all of that good stuff. In our case, we need a “promise“. This allows us to interact with our AJAX requests – well outside our $.

Can we execute run multiple Ajax requests simultaneously in jQuery?

There is a requirement to make multiple AJAX calls parallelly to fetch the required data and each successive call depends on the data fetched in its prior call. Since AJAX is asynchronous, one cannot control the order of the calls to be executed.

What is the difference between Ajax and fetch?

Fetch is a browser API for loading texts, images, structured data, asynchronously to update an HTML page. It's a bit like the definition of Ajax! But fetch is built on the Promise object which greatly simplifies the code, especially if used in conjunction with async/await.


2 Answers

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

like image 162
zerkms Avatar answered Sep 20 '22 16:09

zerkms


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)
});
like image 27
Dustin Getz Avatar answered Sep 19 '22 16:09

Dustin Getz