YDN-DB with multiple deferred

隐身守侯 提交于 2019-12-11 07:43:42

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/19087609/ydn-db-with-multiple-deferred

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!