Question

Im trying to use multiple deferred with jquery $.when but so far no luck, this is my code:

var req = $.when(db.count('items'),db.values('items'),db.get('config', 1));

req.done(function(count,r,config) {
  var currency = config.currency;
  if(count > 0){
    var n = r.length;
    for (var i = 0; i < n; i++) {                   
      var id    = r[i].id;
      var itemId = r[i].itemId;
      console.log('ID: '+id+' itemID: '+itemId+' Currency: '+currency);
    }
  }
});

My sample isn't working so hope you guys can help me, I searched everywhere for a solution. Thanks

Was it helpful?

Solution

I see. I will see how I could implement jquery deferred list. Although ydn-db promise has done, fail and them, etc, it is not $.Deferred instance. An adaptor approach is require.

Currently, use transaction as follow:

var results = {};
var tx_req = db.run(function(tx_db) {
  tx_db.count('items').done(function(x) {
    results.count = x;
  });
  tx_db.values('items').done(function(x) {
    results.values = x;
  });
  tx_db.get('config', 1).done(function(x) {
    results.config = x;
  });
}, ['items', 'config'], 'readonly');

req.done(function() {
  var count = results.count;
  var r = results.values;
  var config = results.config;
  var currency = config.currency;
  if(count > 0){
    var n = r.length;
    for (var i = 0; i < n; i++) {                   
      var id    = r[i].id;
      var itemId = r[i].itemId;
      console.log('ID: '+id+' itemID: '+itemId+' Currency: '+currency);
    }
  }
  results = null;
});

It is a bit messy, but more efficient because all three query run in a single transaction.

EDIT:

Just need to add promise() method that return an object having done, fail and progress functions. Should be doable without much overhead. Basically you can do an adaptor like:

var wrap = function(req) {
  req.promise = function() {
    return req; // Note: req has done, fail and progress functions.
    // however, jquery api demand promise to return a new deferred. 
  }
  return req;
}
$.when(wrap(db.count('items')),wrap(db.values('items')),wrap(db.get('config', 1)));

Here is complete code in jsfiddle.

EDIT:

From release 0.8.1, promise method is added to request object and wrapping is no longer needed. Example.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top